Django Form Validation

Learn via video courses
Topics Covered

Overview

Built-in methods are provided by Django for automatic validation of data of the form. Forms in Django are submitted only if it has a CSRF token. An easy approach is used by it for the form validation in Django. The is_valid() method is defined in the form class of Django and it is for the validation of the data of every field that the form has. If the data in the field is valid then true is returned by it and then it places data into an attribute cleaned_data.

Django Validation Example

models.py

Here we are creating a model Student which has fields student_id, student_name and student_contact.

forms.py

Here we are creating a file named form.py which contains a code for the form.

Instantiate the form

We are instantiating the form and we checking the request whether it is post or not. is_valid() method is used for form validation in Django. It validates the data of the form.

views.py

index.html

Now we are creating a template which will show forms.

We can see our form by starting our server.

form page

Every input field is validated and if validation fails for any input field then it will throw an error.

organised form page

Conclusion

  • Built-in methods are provided by Django for automatic validation of data of the form.
  • The is_valid() method is defined in the form class of Django and it is used for the validation of the data of every field that the form has.