为什么我的form.is_valid()总是返回false?

时间:2016-01-03 09:24:25

标签: python django django-forms django-validation

所以问题是当我在views.py中调用authorSearch和deleteAuthor这两个方法时,form,is_valid()总是返回false。

models.py

class Author(models.Model):
    author_name = models.CharField(max_length=200,primary_key=True)
    def __str__(self):
            return self.author_name

Forms.py

class AuthorForm(forms.ModelForm):
    class Meta:
            model = Author
            fields = ['author_name',]

views.py

def authorSearch(request):
    if request.method=='POST':
            form = AuthorForm(request.POST)
            if form.is_valid():
                  #some processing here
                  return render(request,'authorSearch.html',{})
            else:
                    return HttpResponse('No such Author Found!')
    else:
            form = AuthorForm()
            return render(request,'authorSearch.html',{'form':form})

def deleteAuthor(request):
    if request.method=='POST':
            form=AuthorForm(request.POST)
            if form.is_valid():
                    #some processing here
                    return HttpResponse('Author deleted successfully!')
            else:
                    return HttpResponse('Author deletetion failed!')
    else:
            form=AuthorForm()
            return render(request,'deleteAuthor.html',{'form':form})

authorSearch.html

<div class='container'>
{% if request.method == 'GET' %}
     <form action='' method='POST'>
          <!--Some html here -->
     </form>
{% elif request.method == 'POST' %}
    <!--Some html here -->
{% endif %} 

1 个答案:

答案 0 :(得分:1)

一个疯狂的猜测:你忘记了csrf令牌。

只需打印发送到表单的实际数据和错误,即可查看发生了什么!

def authorSearch(request):
    if request.method=='POST':
        form = AuthorForm(request.POST)
        if form.is_valid():
              #some processing here
             return render(request,'authorSearch.html',{})
        else:
             # you want to check what's happening here
             # something like this (from memory, might be wrong):
             print request.POST
             print form.errors
             print form.non_field_errors

             return HttpResponse('No such Author Found!')
    else:
        form = AuthorForm()
        return render(request,'authorSearch.html',{'form':form})

另外,我个人建议您:

  • 使用Charles或类似内容检查HTTP请求和响应
  • 写测试:))