Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Meta Class in Models - Django
Next article icon

Custom Field Validations in Django Models

Last Updated : 14 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Django, field validation is the process of ensuring that the data entered into a field meets certain criteria. Custom field validation allows us to enforce rules such as checking for specific formats, length restrictions or even more complex conditions, like validating an email to belong to a specific domain.

Validation in django can be done at the model level, meaning that it is executed automatically whenever we create or update an instance of a model. This ensures data integrity without needing to add extra validation logic elsewhere in your code.

Syntax for Custom Validators

field_name = models.Field(validators = [function 1, function 2])

  • validators is a list of validator functions that will be executed when the field value is set.
  • Each validator function accepts a single argument, value, which is the data entered for the field.

Django Custom Field Validation Example

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 ?

Step 1: Define the Model

First, let's define a basic model with a CharField for the email address:

Python
from django.db import models from django.db.models import Model  class GeeksModel(Model):     geeks_mail = models.CharField(max_length = 200) 

Step 2: Create a Validator Function

Now, let’s create a custom validator function that will check whether the email address ends with @gmail.com. If it doesn't, the function will raise a ValidationError.

Python
from django.db import models from django.core.exceptions import ValidationError  # creating a validator function def validate_geeks_mail(value):     if "@gmail.com" in value:         return value     else:         raise ValidationError("This field accepts mail id of google only") 

Step 3: Attach the Validator to the Model Field

Next, we attach this validator function to the geeks_mail field in our model using the validators parameter:

Python
from django.db import models from django.core.exceptions import ValidationError  # creating a validator function def 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]) 

Now, the geeks_mail field will only accept email addresses containing @gmail.com. Any other email address will trigger a ValidationError. 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 "[email protected]". 

Let us check if it gets saved in database. 

custom-field-validations-django-models
Custom Validation

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.


Next Article
Meta Class in Models - Django

N

NaveenArora
Improve
Article Tags :
  • Python
  • Python Django
  • Django-models
Practice Tags :
  • python

Similar Reads

  • Django Models
    A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating, or a
    10 min read
  • Django ORM - Inserting, Updating & Deleting Data
    Django's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and databas
    4 min read
  • Django Basic App Model - Makemigrations and Migrate
    Django's Object-Relational Mapping (ORM) simplifies database interactions by mapping Python objects to database tables. One of the key features of Django's ORM is migrations, which allow you to manage changes to the database schema. What are Migrations in Django?Migrations are files that store instr
    4 min read
  • Add the slug field inside Django Model
    The slug field within Django models is a pivotal step for improving the structure and readability of URLs in web applications. This addition allows developers to automatically generate URL-friendly slugs based on titles, enhancing user experience and search engine optimization (SEO). By implementing
    4 min read
  • Intermediate fields in Django - Python
    Prerequisite: Django models, Relational fields in Django In Django, a many-to-many relationship is used when instances of one model can be associated with multiple instances of another model and vice versa. For example, in a shop management system: A Customer can purchase multiple Items.An Item can
    2 min read
  • Python | Uploading images in Django
    In most websites, we often deal with media data such as images, files, etc. In Django, we can deal with the images with the help of the model field which is ImageField. In this article, we have created the app image_app in a sample project named image_upload. The very first step is to add the below
    5 min read
  • Change Object Display Name using __str__ function - Django Models | Python
    How to Change Display Name of an Object in Django admin interface? Whenever an instance of model is created in Django, it displays the object as ModelName Object(1). This article will explore how to make changes to your Django model using def __str__(self) to change the display name in the model. Ob
    2 min read
  • Custom Field Validations in Django Models
    In Django, field validation is the process of ensuring that the data entered into a field meets certain criteria. Custom field validation allows us to enforce rules such as checking for specific formats, length restrictions or even more complex conditions, like validating an email to belong to a spe
    3 min read
  • Meta Class in Models - Django
    Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. D
    3 min read
  • How to use Django Field Choices ?
    Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for some field. For example, consider a field semester which can have options as { 1, 2, 3, 4, 5, 6 } only. Choices limits t
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences