How to use Regex Validator in Django?
Last Updated :
29 Sep, 2023
Django, a popular web framework, provides a built-in regex validator that allows you to enforce specific patterns on input data. Whether you need to validate user input, form fields, or any other data in your Django application, regex validators can be incredibly useful. In this article, we’ll explore how to use regex validators in Django.
Setting up the Project
Installation: To install Django.
Creating the Project
Create the project by using the command:
django-admin startproject bookstore
cd bookstore
Create an application named ‘mini’ by using the command:
python manage.py startapp mini
Now add this app to the ‘INSTALLED_APPS’ in the settings file.
Structuring Your Project

mini/models.py
This code defines a Django model called Vehicle with a registration_number field. The registration_number field is limited to a maximum length of 10 characters and is validated using a RegexValidator to ensure it follows the specified format. The ‘__str__’ method is provided to display the registration number when you print a Vehicle object.
Python3
from django.core.validators import RegexValidator
from django.db import models
class Vehicle(models.Model):
registration_number = models.CharField(
max_length = 10 ,
validators = [
RegexValidator(
regex = r '^[A-Z]{3}\d{3}$' ,
message = "Enter a valid registration number in the format ABC123." ,
code = "invalid_registration" ,
),
],
)
def __str__( self ):
return self .registration_number
|
mini/view.py
These views work together to allow users to add new vehicles with registration numbers following the specified format and to view a list of all vehicles in the system. The ‘add_vehicle’ view handles form submissions, including regex validation, while the vehicle_list view displays the list of vehicles stored in the database.
Python3
from django.shortcuts import render, redirect
from .models import Vehicle
from .forms import VehicleForm
def add_vehicle(request):
if request.method = = 'POST' :
form = VehicleForm(request.POST)
if form.is_valid():
form.save()
return redirect( 'vehicle_list' )
else :
form = VehicleForm()
return render(request, 'add_vehicle.html' , { 'form' : form})
def vehicle_list(request):
vehicles = Vehicle.objects. all ()
return render(request, 'vehicle_list.html' , { 'vehicles' : vehicles})
|
mini/form.py
By defining VehicleForm in this manner, you are essentially creating a form that is tightly integrated with the Vehicle model.
Python3
from django import forms
from .models import Vehicle
class VehicleForm(forms.ModelForm):
class Meta:
model = Vehicle
fields = [ 'registration_number' ]
|
templates/add_vehicle.html
This file used to add vehicle details.
HTML
<!DOCTYPE html>
< html >
< head >
< title >Add Vehicle</ title >
</ head >
< body >
< h1 >Add Vehicle</ h1 >
< form method = "post" >
{% csrf_token %}
{{ form.as_p }}
< button type = "submit" >Save</ button >
</ form >
</ body >
</ html >
|
templates/vehicle_list.html
This HTML file is used for listing the vehicles.
HTML
<!DOCTYPE html>
< html >
< head >
< title >Vehicle List</ title >
</ head >
< body >
< h1 >Vehicle List</ h1 >
< ul >
{% for vehicle in vehicles %}
< li >{{ vehicle }}</ li >
{% empty %}
< li >No vehicles in the list.</ li >
{% endfor %}
</ ul >
< a href = "{% url 'add_vehicle' %}" >Add Vehicle</ a >
</ body >
</ html >
|
mini/urls.py
Configure your app’s URLs to map to the views you’ve created:
Python3
from django.urls import path
from . import views
urlpatterns = [
path( 'add-vehicle/' , views.add_vehicle, name = 'add_vehicle' ),
path( 'vehicle-list/' , views.vehicle_list, name = 'vehicle_list' ),
]
|
urls.py
Include your app’s URLs in the project’s main urls.py:
Python3
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path( 'admin/' , admin.site.urls),
path( 'vehicles/' , include( 'your_app.urls' )),
]
|
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 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
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
How to Use MaxLengthValidator in Django
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
3 min read
how to use validate_comma_separated_integer_list 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 'validate_comma_separated_integer_list' validator in Django.
4 min read
How to get GET request values in Django?
Django, a high-level Python web framework, simplifies the process of web development. One common task in web applications is handling GET requests, which are typically used to retrieve data from a server. In this article, we'll create a small Django project that displays a message using data from a
2 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
required - Django Form Field Validation
Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments. Some Field classes take additional, field-specific argu
4 min read
label â Django Form Field Validation
Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments. label is used to change the display name of the field.
4 min read
error_messages - Django Form Field Validation
Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments. The error_messages argument lets you specify manual err
4 min read