html - form.is_valid() 返回 false (django)

标签 html django django-forms django-templates django-views

我对 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')

找了很多论坛都没能解决问题。 提前致谢!

最佳答案

注意:-此答案仅用于帮助您调试代码。

您可以直接在 View 中打印表单错误。

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)
      

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

相关文章:

javascript - 在底部 'reaches' 之前滚动 HTML 页面

带有 Ajax 和静态 div 的 jQuery 选项卡

javascript - 动态更改表单上复制输入的 ID 和名称

javascript - 从多个 <select>/<option> 获取值时出现问题

django - 使用 Django 和 South 重命名应用程序

python - 只是无法让 MySQL 与 Python/Django 一起工作

django - 统计特定用户 django 的登录次数?

python - Django:如何使用单选按钮将附加数据链接到选择?

Django 表单; 'bool' 对象没有属性 'get'

django - django 内联表单集的单选按钮