Introduction
Django is one of Python's most popular, trusted, and reliable web development frameworks. With Django, we can quickly create web applications without worrying about installation or dependency problems that we usually find with other frameworks.
This article will learn how to add custom field validations in Django Model using examples. For example, we can add validation for an email field by specifying a particular format. There are multiple ways for achieving custom field validations in Django Model. These Validations are run when we are creating an instance of the model. Technically, the validation is implemented once we run ModelName.objects.create(data = data).
Custom Field Validation in Django Model
Django models have their own built-in validations that we can use while creating models. However, often we require further validations on some fields. Such as the title length, age limit, or coupon code should be in all caps. A custom model validator in such scenarios is the easiest solution.
Custom Field Validations in Django Model are implemented when we create an instance of the model. Basically, the validation is implemented once we run ModelName.objects.create(data = data). The custom field validations in Django Model take a value and raises a ValidationError if it does not meet some criteria.
Syntax:-
field_name = models.Field(validators = [function 1, function 2]) |
Requirements for custom field validation in Django:-
To perform a custom field validation in Django we need a few things.
- Firstly, we will need a Django model to perform validation.
- Next, we need a validator function that will take the field value and return it if it satisfies the custom validation; otherwise, it returns an error message.
- Finally, we need to integrate the validator function with the appropriate field in the Django model.
Example with explanation:-
For example, in this article, we will consider a project named CodingNinjas and an app named codeStudio:
First of all, let's create a Django Model with some validations, In the models.py file of the codeStudio app,
from django.db import models
# Create our models here.
class AuthorDetailModel(models.Model):
Name = models.CharField(max_length = 180)
Author_email = models.CharField(max_length = 200 , )
We have created an AuthorDetailModel with the fields Name and Author_email in the above code. In both fields, we have used the charField validation method to validate the maximum length of the field values using the max_length property.
Now we will apply custom field validation so that the Author_email is a valid coding Ninjas mail ID only. To achieve this, we will create a function that takes a value and checks if the value ends with @codingninjas.com.
In the model.py file,
from django.db import models
# importing validationerror
from django.core.exceptions import ValidationError
# creating a validator function
def validate_codingNinjas_mail(value):
if value.endswith('@codingninjas.com'):
return value
else:
raise ValidationError("This is not a coding ninjas mail ID")
# Create our models here.
class AuthorDetailModel(models.Model):
Name = models.CharField(max_length = 180)
Author_email = models.CharField(max_length = 200 , )
With the above code, we added validate_codingNinjas_mail function to take a value and check if the provided value is a coding ninjas id or not by using the endswith('@codingninjas.com') function of Python.
Now let’s add this validation function as a custom validator in the Author_email field,
from django.db import models
# importing validationerror
from django.core.exceptions import ValidationError
# creating a validator function
def validate_codingNinjas_mail(value):
if value.endswith('@codingninjas.com'):
return value
else:
raise ValidationError("This is not a coding ninjas mail ID")
# Create our models here.
class AuthorDetailModel(models.Model):
Name = models.CharField(max_length = 180)
Author_email = models.CharField(
max_length = 200,
validators =[validate_codingNinjas_mail]
)
Let's create an instance without codingninjas.com and check if the custom field validations in Django model worked or not.
Note: that after every change in models.py, one needs to run migrate and makemigration commands as
|
Python manage.py makemigrations Python manage.py migrate |
Output for an invalid mail ID:

Output for a valid mail ID:





