【问题标题】:Django forms: "This field is required" when file POSTed to file fieldDjango表单:文件发布到文件字段时“此字段是必需的”
【发布时间】:2023-03-17 23:09:01
【问题描述】:

由于某种原因,我无法将文件放入我的 ModelForm 中的文件字段。文件已提交,文件名在相应的 POST 请求中,但 form.is_valid() 失败,因为它声明 {'the_file': [u'This field is required.']}

我为一个模型编写了一个 ModelForm,其中包含一个文件字段和另一个模型的外键,因此:

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'

然后我生成了一个表单来上传文件,因此:

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

当我至少可以做一件事时,进行一些非常基本的验证(这将被扩展!)。

表单是这样处理的:

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 上

【问题讨论】:

    标签: django forms


    【解决方案1】:

    确保您的表单设置了enctype,例如:

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

    来自the docs

    请注意,request.FILES 仅在请求方法为 POST 且发布请求的 &lt;form&gt; 具有属性 enctype=" 时才会包含数据多部分/表单数据”。否则,request.FILES 将为空。

    【讨论】:

    • 非常感谢!我已经阅读了该页面大约 10 次,并在第一次阅读时看到了它,但在其他所有阅读中都错过了它,以找出我错过了什么。继续下一个错误!
    猜你喜欢
    • 2018-09-08
    • 2020-10-10
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多