Table of contents
1.
Introduction
2.
Custom Field Validation in Django Model
2.1.
Syntax:-
2.2.
Requirements for custom field validation in Django:-
2.3.
Example with explanation:-
3.
Frequently Asked Questions
4.
Key Takeaways
Last Updated: Mar 27, 2024

Custom Field Validations in Django Model

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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.

  1. Firstly, we will need a Django model to perform validation.
  2. 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.
  3. 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 , )
You can also try this code with Online Python Compiler
Run Code

 

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 , )
You can also try this code with Online Python Compiler
Run Code

 

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]
                            )
You can also try this code with Online Python Compiler
Run Code

 

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:

Frequently Asked Questions

  1. Can we use one validator function at multiple fields?
    Yes, we can use one validator function to validate multiple fields simultaneously. 
     
  2. What are some built-in validators in Django?
    Django offers us a lot of built-in validators like EmailValidator, URLValidator, validate_ipv4_address, validate_ipv6_address, int_list_validator, MaxLengthValidator, etc. 

Key Takeaways

This article taught us how to implement custom field validations in Django Model using examples. We built our own email validator to add custom field validations in the Django Model email field.

Don't stop here. Check out the blogs Best Django Books, Top 30 Basic Django Interview Questions: Part 1, and Top 30 Intermediate Django Interview Questions: Part 2.

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass