Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django forms: "This field is required" when file POSTed to file field

Tags:

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

like image 936
David Boshton Avatar asked Nov 24 '15 10:11

David Boshton


1 Answers

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.

like image 175
Alasdair Avatar answered Sep 28 '22 08:09

Alasdair