VALIDATION OF THE FORM
Django offers us various ways of validating data. In this post we will look at some of the most common and most used techniques. I leave you a link to the official documentation
https://docs.djangoproject.com/en/4.0/ref/forms/validation/
A first validation is done on the client side, however for security reasons we cannot rely on this validation only (which can be disabled with the novalidate attribute in the form tag) validation is also required on the server side. A first approach can be to go to the FormContatto class and specify the required attribute.
However, the most common procedure for validating a field is to override the clean_field_name method. Before seeing that method let’s see how I changed the contatto.html template to be able to view the validation errors.
Now let’s see how to override the clean_field_name method. Suppose that our TextArea does not accept the word “parola” let’s see how to do it.
The ValidationError method found in the django.core.exceptions namespace is used to raise an exception and invalidate the form. Furthermore, Django makes use of so-called validators (link: https://docs.djangoproject.com/en/4.0/ref/validators/ ) which are used for example to specify the minimum or maximum length or both of a given field.
As you can see I modified the FormContatto to be able to specify some attributes, such as the Bootstrap form-control class and apply a style. Note how with the use of validators the minimum length of the TextArea is set to ten characters.
Leave A Comment