Django形式:“此字段为必填"当文件发布到文件字段时 [英] Django forms: "This field is required" when file POSTed to file field
问题描述
由于某种原因,我无法将文件放入ModelForm中的文件字段中.文件已提交,文件名在相应的POST请求中,但是form.is_valid()
失败,因为它指出{'the_file': [u'This field is required.']}
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.']}
我为一个模型编写了一个ModelForm,其中有一个文件字段,并且有另一个模型的外键,因此:
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.
表单是这样处理的:
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()
这是在Django 1.7上
This is on Django 1.7
推荐答案
确保您的表单具有enctype
设置,例如:
Make sure that your form has the enctype
set, e.g.:
<form method="post" enctype="multipart/form-data">
来自文档 :
请注意, request.FILES 仅在请求方法为 POST 并且发布请求的
<form>
具有属性 enctype ="multipart/form-data" .否则, request.FILES 将为空.
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.
这篇关于Django形式:“此字段为必填"当文件发布到文件字段时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!