Django表示“这个字段是必需的” (甚至文本字段),尽管它已被填充 [英] Django form saying "this field is required" (even text fields) although it's been filled
问题描述
其他一些人以前都有这个问题,但都是文件相关的。对我来说,即使我填写的文本字段(并且必须填写)返回此字段为必需错误,而我已经完成了所有人的建议。看看我的代码:
A few other people have had this problem before but they were all file-related. For me, even text fields that I have filled (and must be filled) return "This Field is Required" error whilst I have done everything people suggested. Have a look at my code:
视图
class MainForm(forms.Form):
name = forms.CharField()
subject = forms.CharField()
text = forms.CharField(widget=forms.Textarea)
file = forms.FileField()
password = forms.CharField()
def mainpage(request):
if request.method == 'POST':
form = MainForm(request.FILES or None, request.POST or None)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponse('Ok')
else:
form = MainForm()
return render(request, "main.html", {'form': form})
def handle_uploaded_file(file):
name = file.name
with open(os.path.join("static\img", "{0}".format(name)), 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
模板:
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>{{ siteTitle }}</title>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/main.css">
</head>
<body>
{% include 'header.html' %}
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
<table>
<ul>
{{ form.as_table }}
</ul>
</table>
<input type="submit" value="Submit" />
</form>
</body>
</html>
应该注意的是,当我将所有内容设置为不需要时,它只返回一个空的表单。
It should be noted that when I set everything to non-required, it just returns an empty form.
感谢您的慷慨帮助。
推荐答案
你的形式是错误的 - request.POST
必须先到:
The order of arguments in your form is wrong - request.POST
must come first:
# request.POST must come before request.FILES.
form = MainForm(request.POST, request.FILES)
另外,需要或无需
。 POST
和 FILES
始终存在于请求对象,即使它们为空。
Also, you don't need the or None
. POST
and FILES
are always present in the request object, even if they are empty.
也不希望表中的 ul
标签:
<table>
{{ form.as_table }}
</table>
这篇关于Django表示“这个字段是必需的” (甚至文本字段),尽管它已被填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!