Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
How to Use MaxLengthValidator in Django
Next article icon

How to Use MaxLengthValidator in Django

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Django, an excessive degree Python web framework, affords a plethora of gear and capabilities to make net development simpler and extra green. One such feature is the MaxLengthValidator, a validation tool that lets you enforce man or woman limits on entering fields for your Django fashions. In this newsletter, we will discover a way to use MaxLengthValidator in Django to make sure that your information stays inside detailed duration constraints.

MaxLengthValidator in Django

Install Django and follow these steps:

Creating the Project Files

To start the project use this command

django-admin startproject microblog
cd microblog

To start the app use this command

python manage.py startapp app

Now add this app to the 'settings.py' in the installed app.

Setting up the Files

app/model.py: In this model, we have a content field with a maximum length of 14 characters, and we've added the 'MaxLengthValidator' to enforce this limit.

Python3
from django.db import models from django.core.validators import MaxLengthValidator  class Message(models.Model):     content = models.CharField(         max_length=140,         validators=[MaxLengthValidator(limit_value=14,                                message="Message is too long")]     )     created_at = models.DateTimeField(auto_now_add=True)      def __str__(self):         return self.content 

app/form.py: It is used to create a form for adding new messages in Django forms

Python3
from django import forms from .models import Message  class MessageForm(forms.ModelForm):     class Meta:         model = Message         fields = ['content'] 

app/views.py: we define two views:

  • home: Displays existing messages in descending order of creation.
  • add_message: Handles adding new messages and enforces the character limit.
Python3
from django.shortcuts import render, redirect from .models import Message from .forms import MessageForm def index(request):     messages = Message.objects.all().order_by('-created_at')     return render(request, 'myapp/index.html', {'messages': messages})  def add_message(request):     if request.method == 'POST':         form = MessageForm(request.POST)         if form.is_valid():             form.save()             return redirect('home')     else:         form = MessageForm()     return render(request, 'myapp/index2.html', {'form': form}) 

Creating GUI for the Project

Create a templates folder and, create 2 files, Here we named it as index.html and index2.html.

index.html: We create HTML templates for displaying messages (index.html) and adding messages (index2.html) in the templates folder.

HTML
<-- index.html --> <!DOCTYPE html> <html> <head>     <title>Microblog</title> </head> <body>     <h1>Microblog</h1>     <ul>         {% for message in messages %}             <li>{{ message.content }}</li>         {% endfor %}     </ul>     <a href="{% url 'add_message' %}">Add Message</a> </body> </html> 

index2.html: This HTML page is used to collect the Information from the user.

HTML
<-- index2.html --> <!DOCTYPE html> <html> <head>     <title>Add Message</title> </head> <body>     <h1>Add Message</h1>     <p>The word limit is 13</p>      <form method="post">         {% csrf_token %}         {{ form.as_p }}         <input type="submit" value="Submit">     </form>     <a href="{% url 'home' %}">Back to Home</a> </body> </html> 

app/urls.py: URLs for the app are defined in app/urls.py, including the homepage and the add message page.

Python3
from django.urls import path from . import views  urlpatterns = [     path('', views.index, name='home'),     path('add/', views.add_message, name='add_message'), ] 

urls.py: We include the app's URLs in the project's urls.py.

Python3
from django.contrib import admin from django.urls import path, include  urlpatterns = [     path('admin/', admin.site.urls),     path('', include('app.urls')), ] 

Deployement of the Project

Migrate your files to the database:

python manage.py makemigrations
python manage.py migrate

Deploy your project

python manage.py runserver

Output:

Add message - maxvalidators

Screenshot-from-2023-09-28-15-05-28



Next Article
How to Use MaxLengthValidator in Django

P

puja2370
Improve
Article Tags :
  • Project
  • Python
  • Geeks Premier League
  • Django
  • Python Django
  • Geeks Premier League 2023
Practice Tags :
  • python

Similar Reads

    How to use URL Validator in Django?
    In Django, a popular Python web framework, URL validation can be easily implemented using built-in tools and libraries. In this article, we will explore how to use the URL validator in Django to ensure that the URLs in your web application are valid and secure. Django's URL ValidatorDjango provides
    3 min read
    How to Do SELECT MAX in Django?
    When working with databases in Django, we often need to find the highest value of a specific field in a model. Let's say, find the book with the highest price, the product with the highest discount, etc. This is like doing a SELECT MAX query in SQL. In this article, we'll learn how to find the max v
    3 min read
    How to use 'validate_email' in Django?
    One crucial aspect of web development is managing user data, and email validation is a common task in this regard. The validate_email function in Django is a handy tool that helps developers ensure the validity of email addresses submitted by users. In this article, we will explore how to use valida
    2 min read
    ValidationError in Django
    Django, a popular Python web framework, is renowned for its robustness and reliability. However, like any software, it can throw errors, and one common error you might encounter is the 'django.core.exceptions.ValidationError.' In this article, we will how to resolve this error. What is 'django.core.
    7 min read
    How to add Pagination in Django Project?
    Pagination system is one of the most common features in  blogs, search engine , list of result etc. Seeing the popularity of pagination system django developers have build a Paginator class so that web developers do not have to think of the logic to make paginators. What is the Paginator Class?The P
    4 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