Ninja Turtle
Ninja Turtle

Reputation: 156

why is my form.is_valid() always returning false?

So the problem is that when i call the two methods authorSearch and deleteAuthor in views.py, form,is_valid() is always returning 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 %} 

Upvotes: 0

Views: 1322

Answers (1)

Fran&#231;ois Constant
Fran&#231;ois Constant

Reputation: 5496

A wild guess: you forgot the csrf token.

Simply print the actual data sent to the form and the errors to see what's happening !

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})

Also, I'd personally recommend you to:

  • use Charles or something similar to check the HTTP requests and responses
  • write tests :)

Upvotes: 1

Related Questions