Custom Field Validations in Django Models - GeeksforGeeks

21 Sep, 2021
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).
Syntax –
field_name = models.Field(validators = [function 1, function 2]) 
Illustration of validators using an Example. Consider a project named geeksforgeeks having an app named geeks.  
Refer to the following articles to check how to create a project and an app in Django. 
How to Create a Basic Project using MVT in Django?
How to Create 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.  
Python3
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model):    geeks_mail = models.CharField(                    max_length = 200,                     )
Now we will apply a custom validation so that the above field is validated for google mail IDs only. Create a function that 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. 
Python3
from django.db import models# importing validationerrorfrom django.core.exceptions import ValidationError # creating a validator functiondef validate_geeks_mail(value):    if "@gmail.com" in value:        return value    else:        raise ValidationError("This field accepts mail id of google only")  # Create your models here.class GeeksModel(models.Model):    geeks_mail = models.CharField(max_length = 200)
Now let us add this function as a validator in our field. Note that one validator function can be used for multiple fields simultaneously. 
Python3
from django.db import models# importing validationerrorfrom django.core.exceptions import ValidationError # creating a validator functiondef validate_geeks_mail(value):    if "@gmail.com" in value:        return value    else:        raise ValidationError("This field accepts mail id of google only")  # Create your models here.class GeeksModel(models.Model):    geeks_mail = models.CharField(                         max_length = 200,                         validators =[validate_geeks_mail]                         )
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 commands. In your browser go to http://localhost:8000/admin/geeks/geeksmodel/add/ and enter “abc@geeksforgeeks.org”. 
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 value. 
sweetyty
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python