30

I for some reason am unable to get a file to into my filefield in my ModelForm. The file is submitted and the file name is in the corresponding POST request, however the form.is_valid() fails as it states {'the_file': [u'This field is required.']}

I have written a ModelForm for a model with a file field in and a foreign key to another model, thus:

class AccountFile(models.Model):
the_file = models.FileField(upload_to='{}/%Y/%m/%d/'.format(
    settings.MEDIA_ROOT,
))
account = models.ForeignKey(
    Account,
    blank=True,
    null=True,
    related_name='account_files'

I've then generated a form to upload a file, thus:

class UploadFileForm(forms.ModelForm):
class Meta:
    model = models.AccountFile
    fields = ['the_file' ]


def clean_file(self):
    file = self.cleaned_data.get("the_file", False)
    filetype = magic.from_buffer(file.read())
    if not "pdf" in filetype:
        raise forms.ValidationError("File is not pdf.")
    return file

Putting in some very basic validation (which will be extended!) when I can get at least one thing to work.

The form is processed like this:

if request.method == 'POST':
    form = forms.UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        handle_uploaded_file(request.FILES['file'])
        return redirect(
            'account_url',
            acc_manager_pk=acc_manager.pk,
            account_pk=account.pk,
            )
else:
    form = forms.UploadFileForm()

This is on Django 1.7

Alasdair
  • 298,606
  • 55
  • 578
  • 516
David Boshton
  • 2,555
  • 5
  • 30
  • 51

1 Answers1

72

Make sure that your form has the enctype set, e.g.:

<form method="post" enctype="multipart/form-data">

From the docs:

Note that request.FILES will only contain data if the request method was POST and the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • 7
    Thanks so much! I've read that page about 10 times and saw that on the first read but then missed it on every other read to find out what I had missed. On to the next error! – David Boshton Nov 24 '15 at 10:50
  • Make sure you notice the request.FILES above ... this needs to be used when initializing your form in a POST request (add_document_form = AddDocumentForm(request.POST, request.FILES). I always forget this part. – Harlin May 31 '22 at 18:36