Alex Rivera | Logout

How to upload a file with Django

Asked 2011-10-05T15:54:53.213
9

I'm trying to write form to upload a file with Django. The admin form works just fine, but the problem is that after I click submit on my form, the form loses the file that I selected (filename disappears and 'No file chosen' appears next to 'Choose File' button), and the view won't validate the form because the file is missing. My form/view/file handler look just like the 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+')
    for 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 Me
Edit
Report

1 Answer

7

Change this...

handle_uploaded_file(request.FILES['file'])

To this...

handle_uploaded_file(request.FILES['attachment'])

The file is stored in the POST data with the name of your field.

answered 2011-10-05T16:30:34.580

Your Answer