How to upload a file with Django -


i'm trying write form upload file django. admin form works fine, problem after click submit on form, form loses file selected (filename disappears , 'no file chosen' appears next 'choose file' button), , view won't validate form because file missing. form/view/file handler django example.

forms.py

class attachform(forms.modelform):     class meta:             model = attachment             exclude = ('insp', 'contributor', 'date') 

views.py

def handle_uploaded_file(f):     destination = open('some/file/name.txt', 'wb+')     chunk in f.chunks():         destination.write(chunk)     destination.close()  def attach(request, insp_id):     if request.method == 'post':             form = attachform(request.post, request.files)             if form.is_valid():                     handle_uploaded_file(request.files['file'])                     f = form.save(commit=false)                     f.contributor = request.user                     f.insp = insp_id                     f.save()                     return httpresponseredirect(server + '/inspections/' + str(insp_id) + '/')     else:             form = attachform()     return render_to_response('attach.html', locals(), context_instance=requestcontext(request)) 

models.py

class attachment(models.model):     insp = models.foreignkey(inspection)     contributor = models.foreignkey(user, related_name='+')     date = models.datetimefield()     title = models.charfield(max_length=50)     attachment = models.filefield(upload_to='attachments')     def __unicode__(self):         return self.title     def save(self):         if self.date == none:             self.date = datetime.now()         super(attachment, self).save()     class meta:         ordering = ['-date'] 

attach.html

{% extends "base.html" %}  {% block title %}add attachment{% endblock %}  {% block content %} <h2>attach file: inspection {{ insp_id }}</h2> <p>this form used attach file inspection.</p> <form action="." method="post" autocomplete="off">{% csrf_token %}     <table cellspacing="10" cellpadding="1">         {% field in form %}             <tr>             <th align="left">                                {{ field.label_tag }}:             </th>             <td>                 {{ field }}             </td>             <td>                 {{ field.errors|striptags }}             </td>         </tr>         {% endfor %}         <tr><td></td><td><input type="submit" value="submit"></td></tr>     </table> </form> {% endblock %} 

any ideas of doing wrong?

change this...

handle_uploaded_file(request.files['file']) 

to this...

handle_uploaded_file(request.files['attachment']) 

the file stored in post data name of field.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -