![]() |
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 ProjectInstallation: To install Django. Creating the ProjectCreate the project by using the command: django-admin startproject 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 Projectmini/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
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
mini/form.py By defining VehicleForm in this manner, you are essentially creating a form that is tightly integrated with the Vehicle model. Python3
templates/add_vehicle.html This file used to add vehicle details. HTML
templates/vehicle_list.html This HTML file is used for listing the vehicles. HTML
mini/urls.py Configure your app’s URLs to map to the views you’ve created: Python3
urls.py Include your app’s URLs in the project’s main urls.py: Python3
Output |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 9 |