用Django写上传文件功能,但是文件总是上传不到后台。form表单并没有得到数据,找了很多资料也不知道为什么。与这位博主问题类似
表单定义
class UserInfo(forms.Form):
country = forms.CharField(label='country', max_length=200)
email = forms.EmailField(label='email')
filetoupload = forms.FileField(label='fileToUpload')
views.py文件代码
def receiveinfo(request):
if request.method == 'POST':
form = UserInfo(request.POST, request.FILES)
print form
print form.is_valid()
if form.is_valid():
# process the data in form.cleaned_data as required
store = form.cleaned_data['store']
country = form.cleaned_data['country']
email = form.cleaned_data['email']
return HttpResponse('/thanks/')
else:
return render(request, 'home.html', {'form': form})
else:
form = UserInfo()
return render(request, 'home.html', {'form': form})
在运行程序后print 的表单信息
<tr><th><label for="id_country">country:</label></th><td><input type="text" name="country" value="DE" required id="id_country" maxlength="200" /></td></tr>
<tr><th><label for="id_email">email:</label></th><td><input type="email" name="email" value="cg123456@163.com" required id="id_email" /></td></tr>
<tr><th><label for="id_filetoupload">fileToUpload:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="file" name="filetoupload" required id="id_filetoupload" /></td>
</tr>
home.html代码
<form class='UserInfo' action="submit" method="post" enctype="multipart/form-data">{% csrf_token %}
E-mail: <input type="email" name="email" autofocus><br>
{{ form.email.errors}}<br>
Country: <input list="countrycode" name="country">
{{ form.email.errors}}<br>
<datalist id="countrycode">
<option value="DE">
<option value="ES">
<option value="FR">
<option value="IT">
<option value="UK">
<option value="JP">
<option value="CA">
<option value="USA">
</datalist>
<br>
Select a file to upload:
<input type="file" name="fileToUpload" id="fileToUpload" ><br>
{{ form.filetoupload.errors}}<br>
<input type="submit"><br>
</form>
通过views.py中 print form的信息,可以看出,post并没有得到文件信息。可是我找不到问题在哪?
是还有settings.py 文件要设置吗?在官方文档里面没有看懂。
放了
{% csrf_token %}
吗?