This article revolves around how to add custom validation to a particular field. For example to add validation of an email to a CharField by specifying a particular format. There can be multiple ways on how to achieve custom validation. In this article, we are going to show it from the model itself so that you need not manipulate it elsewhere.
These Validation are run when you are trying to create an instance of a model. Technically, this validation is implemented after you run
ModelName.objects.create(data = data).
field_name = models.Field(validators = [function 1, function 2])
Django Custom Field Validation Explanation
Illustration of validators using an Example. Consider a project named
geeksforgeeks having an app named
Refer to the following articles to check how to create a project and an app in Django.
Enter the following code into
models.py file of geeks app. We will be using CharField for experimenting for all field options.
Now we will apply a custom validation so that the above field is validated for google mail IDs only. Create a function which accepts an argument called value. One can apply any type of operation on value now. so let us check if our function value contains @gmail.com to be validated for google mail IDs only.
Now let us add this function as a validator in our field. Note that one validator function can be used for multiple fields simultaneously.
Let us try to create an instance without gmail.com and check if our validation worked or not. Note that after every change in models.py one needs to run makemigrations and migrate commmands.
In your browser go to http://localhost:8000/admin/geeks/geeksmodel/add/ and enter “email@example.com”.
Let us check if it gets saved in database.
So the validation worked and this field can only accept email ids ending with @gmail.com. This way one can apply any kind of custom validation on
- Built-in Field Validations - Django Models
- Django form field custom widgets
- Django Models | Set - 1
- Django Models | Set - 2
- Python | Relational fields in Django models
- BigIntegerField - Django Models
- AutoField - Django Models
- BigAutoField - Django Models
- BooleanField - Django Models
- CharField - Django Models
- DateField - Django Models
- DateTimeField - Django Models
- DecimalField - Django Models
- BinaryField - Django Models
- EmailField - Django Models
- DurationField - Django Models
- FileField - Django Models
- FilePathField - Django Models
- FloatField - Django Models
- ImageField - Django Models
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.