Django Forms -Part 3 Validations

Robin Thakur
4 min readJun 4, 2018
http://m.memegen.com/syj8ef.jpg

Till now we have seen how to render basic and model forms in django , I mean what all happens on the front-end . We so far have no idea how django manages to extract meaningful data out of these forms and validates them . And yes if you have not yet seen the last 2 articles , I would suggest you to do the same . Any ways lets dive in !

So as soon as you hit the SUBMIT button ( which should be an input element ) your form gets submitted to the view which rendered it . So , it is now your job to deal with it !

A line that you will often see in django views is

form=FormClass(request.POST or None)

where the FormClass is the class of your form . This is equivalent to saying :

Once you have the form instance created you can start working with the data.

Validation of a form is split into the following functions and usually begins once the form.is_valid() call is made. During each step we can raise a ValidationError with an appropriate message:

  • The to_python() method is first applied on each field of the form . This converts the form data to the appropriate python objects . In case of any compatibility issues a ValidationError is raised . example- Submitting the age as a string of characters rather than an Integer field.
  • The validate method that handles field specific validations .
Taken from the django docs

We have overridden the to_python and the validate methods.

  • The clean method that is specific to a field subclass . This function will run the previous 2 functions and raise any ValidationErrors . So basically this method checks for the fact that the data is given in the format as specified ie if it is syntactically correct.Example : If we want the user to enter space or comma separated strings it is in this function we should VALIDATE that . This function should return the appropriate python object which forms the part of the cleaned_data dictionary .This is use to extract the data from the submitted form by its field name . eg- form.cleaned_data.get(‘username’).
  • clean_<fieldname> method does any cleaning that is required for the form subclass’s <fieldname> field. This has got nothing to do with the TYPE of the <fieldname> ie Suppose we had a field for email input .So the previous function ie clean method of step 3 ensures the correct syntax of the email field by means of , say a complex regular expression . However this function may check if the email belongs to a particular list of emails or not . The value of the email field from the form is available to this function by now because the previous function returned it to the cleaned_data dictionary.Again, make sure that your function returns the appropriate data because it is to take the new value for the field in the cleaned_data dictionary .In the picture below the function returns data which will now take the value of recipients in the cleaned_data dictionary.
Example of form subclass clean_<fieldname>

The clean method for the form subclass does the cleaning on the form level ie if somehow 2 fields are related . Example:We have the user enter password1 and password2 . It is inside this function that we check that the 2 passwords are equal .

Let me extend this example to give you a brief summary of what we learnt so far:

Suppose inside your form you have 3 fields namely username ,password1 and passwprd2 . So once the form is submitted , the first thing that happens is that passwords and the username are converted to python objects, strings in this case . Next we will have our clean function for the field subclass (example- CharacterField , IntegerField , etc. ) that just checks if the password is a combination of alphabets , numerals and special characters . Next comes the turn of the clean method for form subclass . If we have a function clean_<fieldname> , it is called . Here we can check say,if the username is unique by defining a function clean_username() ,else we directly move to the clean function for the form subclass where the 2 passwords are checked against each other .

So basically the field subclass based functions check to see if the input is syntactically correct and the form subclass fields check to see if the input matches the logic of your application.

Thus, all this happens under the hood once you call the is_valid function from your view . If no ValidationErrors are found you can move on .

If your form is a model Form just do form.save() as we saw previously and if not use something like Profile.objects.create( the required data ) .

Note that if your form has passwords , always use the set_password method ie

 instance=form.save(commit=False)
password=form.cleaned_data.get(‘password’)
instance.set_password(password)
instance.save()

So , that was all about django form validations . In the next article we will see how to render the Validation errors generated by these forms , inside your templates .

I bid you farewell .

--

--