我对django有点新鲜。我在上传时选择将文件发送到另一台服务器,但form.is_valid()
始终返回false会让我输入if
views.py
-
def sent(request):
if request.method == 'POST':
form = SendFileForm(request.POST, request.FILES)
print "form is made"
print form.errors
if form.is_valid():
print "form is valid"
new_song = Song(songfile= request.FILES['songfile'])
new_song.save()
print "new song is made and saved"
l = List()
#cd = form.cleaned_data
#SENDS THE FILE TO SERVER GIVEN PATH
l.all_files(new_song.songfile.path)
return HttpResponseRedirect(reverse('get_files.views.sent'))
else:
print "form is not valid"
else:
form = SendFileForm()
songs = Song.objects.all()
return render_to_response('sent.html', {'songs': songs,'form': form}, context_instance=RequestContext(request))
sent.html
模板 -
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action={% url "sent" %} method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.songfile.label_tag }} {{ form.songfile.help_text }}</p>
<p>
<!--{{ form.songfile.errors }}-->
{{ form.songfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
forms.py
-
class SendFileForm(forms.Form):
path = forms.CharField()
songfile = forms.FileField(label='Select a music file',help_text='max. 4 megabytes')
我搜索过许多论坛但无法解决问题。 提前谢谢!
答案 0 :(得分:5)
默认情况下,表单中的每个字段都是必需的(required=True
)。未在必填字段中提供信息的表格无效。您可以在模板中将path
字段添加到表单中,并且必须填写该字段,或者您可以创建不需要的路径:
class SendFileForm(forms.Form):
path = forms.CharField(required=False)
...
或
<form action={% url "sent" %} method="post" enctype="multipart/form-data">
...
{{ form.songfile }}
{{ form.path }}
...
</form>
答案 1 :(得分:1)
问题是模板中没有path
输入。您的request.POST
包含不完整的数据,这就是您的表单无效的原因。
模板中缺少这个:
{{ form.path }}
答案 2 :(得分:1)
注意:-此答案仅用于帮助您调试代码。
您可以直接在视图中打印表单错误。
class YourFormView(generic.edit.CreateView):
def post(self, request, *args, **kwargs):
form = YourForm(request.POST)
for field in form:
print("Field Error:", field.name, field.errors)