For some reason, I cannot get the file in my file field in ModelForm. The file is sent and the file name is in the corresponding POST request, but it form.is_valid()fails because it indicates{'the_file': [u'This field is required.']}
I wrote ModelForm for a model with a file field and a foreign key to another model, this way:
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'
Then I created a form for uploading a file like this:
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
We introduce some basic check (which will be expanded!) When I can get at least one thing to work with.
The form is processed as follows:
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
source
share