Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - form has no errors but form.is_valid() doesn't validate

I have a form that for some reason it it doesn't throw any errors (if user adds data in the text field) but form.is_valid() doesn't validate. Any ideas?

forms.py:

class MyForm(forms.Form):     title = forms.CharField(widget=forms.TextInput(attrs={'class':'titleField'))  

mytemplate.html

  <form action="" method="post" name="form">{% csrf_token %}   {{ form.title.errors }}   {{ form.title }}   <input type="submit" name='submit_button' value="Post" />   </form> 

views.py:

      if 'submit_button' in request.POST:             form = MyForm(request.POST)             if form.is_valid():                cd = form.cleaned_data                 title = cd['title']                g = MyData(title='title')                   g.save()         else:             form = MyForm()  
like image 203
avatar Avatar asked Apr 01 '11 16:04

avatar


People also ask

How to validate fields in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What method can you use to check if form data has changed when using a form instance?

Use the has_changed() method on your Form when you need to check if the form data has been changed from the initial data. has_changed() will be True if the data from request.

What is form as_ p in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.

What is clean in Django?

The clean() method on a Field subclass is responsible for running to_python() , validate() , and run_validators() in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError , the validation stops and that error is raised.


2 Answers

From your template, add the following:

{{ form.errors }} {{ form.non_field_errors }} 

Do you see any errors from the above?

like image 72
Thierry Lam Avatar answered Oct 11 '22 15:10

Thierry Lam


You can also print (or log) error at back end too, Similarly use this:

Like, to print error:

print(form.errors) 
like image 32
enigma Avatar answered Oct 11 '22 14:10

enigma