6

I have a model with a FileField in it:

class DocumentUpload(models.Model):
    document_name = models.CharField(max_length=100, blank=True)
    document_path = models.FileField(upload_to='uploads')

and a form which uses this model

class DocumentUploadForm(forms.ModelForm):
    class Meta:
        model = DocumentUpload

When I use the form to create a new upload everything works fine.

    if request.method == 'POST':
        form = DocumentUploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()

However when I try and update/edit the entry it updates all the fields apart from the document which is uploaded. This just stays the same as the original upload.

d = get_object_or_404(DocumentUpload, pk=id)

if request.method == 'POST':
    form = DocumentUploadForm(data=request.POST, files=request.FILES, instance=d)
    if form.is_valid():
        u = form.save()

How do I get it to change the upload file when editing the instance?

Thanks

John
  • 21,047
  • 43
  • 114
  • 155
  • 1
    Is your form template enctype="multipart/form-data" ? – Brant Apr 27 '10 at 13:39
  • That was the problem I Can't believe I missed it. Thanks – John Apr 27 '10 at 13:55
  • I am digging up an old post, as I am having the same problem. I already have `enctype="multipart/form-data"` in my form, so that wouldnt be the solution. HOwever, I am curious about the `data=` what does this refer to in your code? my code is very similar to yours with the exception of this, so I am wondering if this could be the key. – PhilM Oct 21 '22 at 12:38

2 Answers2

7

Since it was my idea, I'll post it up as an answer (just to stroke my own ego and/or rating)...

Add the following to your form's template:

enctype="multipart/form-data"

feel free to check it off as an answer...

:)

Brant
  • 5,721
  • 4
  • 36
  • 39
0

just needed to add:

enctype="multipart/form-data" 

to my form. Thanks Brant

John
  • 21,047
  • 43
  • 114
  • 155