填写表格时,我得到“此字段必填”。即使所有字段都已填写。
这与设置为False或类似的设置无关,因为所有字段都是必需的。
views.py
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
title = form.cleaned_data['title']
username = request.user.get_username()
category = form.cleaned_data['category']
handle_uploaded_file(request.FILES['file'],title,username,category)
return HttpResponseRedirect('')
else:
form = UploadFileForm()
return render(request, 'main/upload.html', {'form': form})
功能
def handle_uploaded_file(f,title,username,category):
with open('/uploads/' + category + '/' + title, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
forms.py
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
category = forms.CharField(max_length=50)
file = forms.FileField()
upload.html
{% extends 'base.html' %}
{% block title %}Upload{% endblock %}
{% block content %}
{% if user.is_authenticated %}
Uploading as: {{ user.username }}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit"/>
</form>
{% else %}
<p>You are not logged in</p>
<a href="{% url 'login' %}">login</a>
{% endif %}
{% endblock %}
我填写表格时遇到的错误是:“此字段为必填字段”
屏幕截图:
当我选择一个文件并引发错误时,它会取消选择我选择的任何文件,类似于在未注册每个字段的情况下点击注册时清除密码字段的方法。
答案 0 :(得分:2)
文件未与请求一起提交,因为您没有在enctype
元素上发送正确的form
。这里是Django's docs所涉及的。
<form method="post" enctype="multipart/form-data">
验证/调试的一种方法是在调用form.data
之前打印表单的数据is_valid
,request.POST和/或request.FILES。或在浏览器的开发工具中验证请求。