我对 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')
我已经搜索了很多论坛,但无法解决问题。先感谢您!
原文由 Badi8beach 发布,翻译遵循 CC BY-SA 4.0 许可协议
默认情况下,表单中的每个字段都是必需的 (
required=True
)。提交的表格在必填字段中没有信息是无效的。您可以将path
字段添加到模板中的表单中,并且必须填写该字段,或者您可以使路径不是必需的:要么