首页 > 解决方案 > 此字段是必需的错误,但字段在表单中

问题描述

所以我有一个用 request.POST 初始化的表单,但是,即使表单有正确的字段,它也是无效的,我错过了什么?

def some_view(self, request):
    form = SomeForm(request.POST or None)
    if form.is_valid():

(Pdb) form.data
<QueryDict: {u'csv_file': [u'some_csv_file.csv'], u'csrfmiddlewaretoken': [u'csrftoken']}>
(Pdb) form.is_valid()
False
(Pdb) form.errors
{'csv_file': [u'This field is required.']}

标签: pythondjangodjango-forms

解决方案


当您在 Django 表单中有一个 FileField 时,有两件事要做:

1. In your template, in the form tag, add enctype="multipart/form-data"
    <form method="POST" action="" enctype="multipart/form-data">

2. Pass the request.FILES when creating the form
    form = SomeForm(request.POST or None, request.FILES)

推荐阅读