How to Use MaxLengthValidator in Django
Last Updated :
24 Apr, 2025
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:


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
4 min read
How to Extend User Model in Django
Djangoâs built-in User model is useful, but it may not always meet your requirements. Fortunately, Django provides a way to extend the User model to add additional fields and methods. In this article, we'll walk through the process of extending the User model by creating a small web project that dis
3 min read
How to Use "get_or_create()" in Django?
In Django, the get_or_create() method is a convenient shortcut for retrieving an object from the database if it exists, or creating it if it doesnât. This method is especially useful when you want to avoid raising exceptions when querying objects and need to ensure an instance is always available. U
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
3 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. Paginator Class live in django/c
5 min read
verbose_name - Django Built-in Field Validation
Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. verbo
3 min read
How to Make Many-to-Many Field Optional in Django
In Django, many-to-many relationships are used when a model can have relationships with multiple instances of another model and vice versa. For example, a book can have many authors, and an author can have written many books. To handle these kinds of relationships, Django provides the ManyToManyFiel
5 min read
how to use validate_ipv4_address in django
A validator is a callable that takes a value and raises a ValidationError if it doesnât meet the criteria. Validators can be useful for re-using validation logic between different types of fields. In this article, we will learn how to use the 'validate_ipv4_address' validator in Django. Required Mod
3 min read