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