Updated May 23, 2023
Introduction to Django Validators
Validators can be used in Django at the model level or the level of the form. These validators are responsible for validating a field. The validators help to analyze the nature of the field with the value filled in the field. More importantly, these validators adjudicate the passed data and post the errors onto the screen. This is the key benefit of Django validators. You can use clean() or field-level validators for Django validators. It depends on the validator message used.
Syntax:
Raise validationerror("")
The process of raising a validation error occurs through validators. You can achieve this by using the validation error exception, which you can raise at both the form level and the field level. Here using this will raise the error and display it on the console. Place the message to be raised between double quotes. The value within the double quotes will display as the error message. Methods like clean() or even clean_fieldname can raise these validation-based errors. You can use validation errors to check all fields across the forms section. The error message displayed on the screen from the syntax will greatly assist in determining the type of message being printed.
Create a Django Validator
Given below shows the creation of the Django validator:
1. Changes in Models.py file
As the syntax section mentions, the email field must be declared in the models.py file. It is noticeable that the email field is declared as the age field in the model. In this case, the email field will be retrieved by default from the user table, which is an inbuilt table associated with four different fields. The fields are username, password, email, password confirmation, etc. These fields will be displayed using the form display used. The user table is an inbuilt table associated with four different fields.
models.py:
from django.db import models
from django.contrib.auth.models import User
# Model variables
# Create your models here.
class Bride(models.Model):
Django_Validators_Example_name = models.CharField(max_length=200,null=True)
Django_Validators_Example_thegai = models.CharField(max_length=200,null=True)
Django_Validators_Example_State = models.CharField(max_length=50,null=True)
Django_Validators_Example_District = models.CharField(max_length=50,null=True)
Django_Validators_Example_Address = models.TextField(null=True)
Django_Validators_Example_Phone = models.BigInteger_Example_Field(null=True)
Django_Validators_Example_profession = models.CharField(max_length=200,null=True)
Django_Validators_Example_salary = models.BigInteger_Example_Field(null=True)
Django_Validators_Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Django_Validators_Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
Django_Validators_Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Django_Validators_Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Django_Validators_Example_Rasi = models.CharField(max_length=200,null=True)
Django_Validators_Example_Nakshatra = models.CharField(max_length=200,null=True)
def __str__(self):
return self.name
2. Changes in Settings.py file
Make sure you correctly set all the values and database connections in the settings.py file to ensure flexible execution of the project. In addition, appropriately declare the mentioned middleware items in the settings.py file as these middlewares are responsible for the application’s functioning during the processing of GET and PUT messages. Additionally, the templates used also need to fill so that the template processing happens in the background.
Settings.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Matrimony.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Template_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'render_dict_processors': [
'django.template.render_dict_processors.debug',
'django.template.render_dict_processors.request',
'django.contrib.auth.render_dict_processors.auth',
'django.contrib.messages.render_dict_processors.messages',
],
},
},
]
3. Changes in the url.py file
Add the signup page here using the URL function. Use the views.sign_up_request to render the sign-up page when necessary. The page named “registered” facilitates user registration.
url.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from matrimony_pages import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$',views.Welcome_page,name='Welcome_page'),
url(r'Mainpage/',views.Main_page,name='Main_page'),
url(r'form/',views.form_view,name='form_view'),
url(r"signup/", views.Sign_up_request, name="register"),
url(r"login/", views.login_request, name="login"),
path(r'profile//',views.Integer_Field_Example_page,name='profile'),
url(r'logout/',views.logout_request,name='logout'),
url(r'reg/',views.Integer_Field_Example_reg_user,name='reg'),
path(r'update//',views.form_update,name='update'),
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
4. Changes in forms.py
The forms.py has the actual validations in place. The validations are implemented in the NewuserForm. This form serves as a signup request and includes validation rules for the email field. It verifies the input values and throws an error if the email field contains any unexpected values.
views.py
from django import forms
from .models import Bride
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
# Create your forms here.
Rasi_CHOICES =(
("1", "Mesham"),
("2", "Rishabam"),
("3", "Mithunam"),
("4", "Kadakam"),
("5", "Simmam"),
("6", "Kanni"),
("7", "Thulam"),
("8", "Viruchikam"),
("9", "Thanusu"),
("10", "Makaram"),
("10", "Kumbam"),
("10", "Meenam"),
)
State_Choices = (
("1", "Mesham"),
("1", "Mesham"))
class Valueform(forms.ModelForm):
Rasi = forms.ChoiceField(choices = Rasi_CHOICES)
class Meta:
model = Bride
fields = "__all__"
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True,error_messages={'required': 'Please enter your name'})
def clean(self):
cleaned_data = super(NewUserForm, self).clean()
email_passed = cleaned_data.get("email")
if not "gmail.com" in email_passed:
print("came here")
raise forms.ValidationError("Sorry, the email submitted is invalid. All emails have to be registered on this domain only.")
return email_passed
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
5. Formulate an HTML file for displaying the signup form
You need to make changes to the HTML pages.
signuppage.html:
<!DOCTYPE html>
<html style="font-size: 16px;">
<head>
<title>Sign_up</title>
</head>
<body class="body">
<nav class='navbar'>
<div class='navbar_div'>
<a class="navbar" onclick="redirect2()" >Home! </a>
<a class="navbar" onclick="redirect2()" >Contact</a>
</div>
</nav>
<body class="body">
<nav class='navbar'>
<div class='navbar_div'>
<a class="navbar" onclick="redirect2()" >Home! </a>
<a class="navbar" onclick="redirect2()" >Contact</a>
</div>
</nav>
{% block content %}
<!--Sign_up-->
<div class="container py-5">
<h1>Sign_up</h1>
<form method="POST">
{% csrf_token %}
{{ Sign_up_form }}
<button class="btn btn-primary" type="submit">Sign_up</button>
</form>
<p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p>
</div>
{% endblock %}
<script>
function form1() {
window.location.href = "http://127.0.0.1:8000/form";
}
function redirect1() {
window.location.href = "http://127.0.0.1:8000/Mainpage";
}
function redirect2() {
window.location.href = "http://127.0.0.1:8000/";
}
</script>
</body>
</html>
Output:
Conclusion – Django Validators
This article portrays how the email field can be docilely professed in a Django setup. The variations can be rendered to an html page with validation errors populated onto the screen when a bad value has been placed.
Recommended Articles
We hope that this EDUCBA information on “Django Validators” was beneficial to you. You can view EDUCBA’s recommended articles for more information.