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()
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.
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.
{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.
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.
From your template, add the following:
{{ form.errors }} {{ form.non_field_errors }}
Do you see any errors from the above?
You can also print (or log) error at back end too, Similarly use this:
Like, to print error:
print(form.errors)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With