之前有一些人遇到过这个问题,但他们都与文件有关。对我来说,即使我填写(并且必须填写)的文本字段也会返回"此字段是必需的"我完成了人们建议的所有事情。看看我的代码:
视图
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>
应该注意的是,当我将所有内容设置为非必需时,它只返回一个空表单。
感谢您的慷慨帮助。
答案 0 :(得分:2)
表单中参数的顺序错误 - request.POST
必须先出现:
# request.POST must come before request.FILES.
form = MainForm(request.POST, request.FILES)
另外,您不需要or None
。 POST
和FILES
始终存在于request object中,即使它们是空的。
您可能也不希望表格中包含ul
个标记:
<table>
{{ form.as_table }}
</table>