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