How to Externally Validate Django Form Data 


               


How to Externally Validate Django Form Data



Python


In this article, we show how to externally validate Django form data.

What is meant by externally validating form data is that we use our functions to validate.

Django has built-in modules to internally validate data such as make sure that the email is a valid email (with EmailField), or to make sure that an integer is a valid integer (with IntegerField).

But what if it's somewhat more complex such as the integer can only be 18 to 64, or you want to give a custom text output to the user if the integer is a certain value.

For functions such as these, you want to externally validate form data in Django, so that we can build custom functions to validate data.

So below, we'll create a basic form called VotersData and we'll have the fields first name, last name, and age.

In order to vote, for this form, you have to be 18 years of age or older.

So, we're going to write code so that only those who are 18 or older can vote, so the form will go through for those 18 and older and for those younger than 18, we'll have a message saying, "You must be at least 18 years old to vote"

So, let's look at the form in the forms.py file.


forms.py File

Below is the code of the VotersData form.



So you can see we have 3 fields, first_name, last_name, and age.

first_name and last_name are of type CharField

age is of type IntegerField.

Since age is of type IntegerField, Django will internally validate that is an integer, so we don't have to worry about that. However, since we only wants ages 18 or greater to validate, we create an external function.

And we create this external function right within the same forms.py file.

We create it right under.

So we create a function. The function name has to start with clean_ and is followed by the name of the field of the form.

Since we are validating the age field, the full line is, def clean_age(self):

After we do this, we create a variable, it can be anything but we'll call it age, just as before.

So we set age equal to self.cleaned_data.get("age")

This gets the internally validated age that was entered into the form field.

We then have a simple if statement that if the age is less than 18, we raise a validation error and output that, "You must be at least 18 years old to vote"

So this is basically the pattern to externally validate data in Django with Python using your own custom functions on top of Django's internal validation.

So if Django doesn't have some built-in way to validate data, you can just do it on your own by making your own custom function.

And this is how form data can be externally validated in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...