这是我的第一个Django项目,我无法在表单中获取值。我创建了一个UploadFileForm,在Views中实现了一些基本代码,并在urls.py中映射了url。当我尝试将输入发送到表单时,我的问题就出现了。即使我的表单已填满,也会给我一个错误,说明字段未填写。我已将问题缩小到' form.is_valid'功能。我的代码中是否缺少某些内容?
upload.html
<form action="{% url 'upload_file' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
{{ form.errors }}
{{ form.non_field_errors }}
<input type="submit" value="OK">
</form>
form.py
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import UploadFileForm
def success(request):
return render(request, 'success.html')
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('success/')
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
def handle_uploaded_file(f):
with open('uploaded.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
urls.py
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^upload/success/', views.success, name='success'),
url(r'^upload/$', views.upload_file, name='upload_file'),
]