我对django有点陌生。我试图在上传后选择将文件发送到另一台服务器,但是form.is_valid()总是返回false不会让我输入ifviews.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')

我搜索了很多论坛,但无法解决问题。
先感谢您!

最佳答案

默认情况下,表单中的每个字段都是必需的(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>

关于html - form.is_valid()返回false(Django),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20723646/

10-13 02:52