Introduction to Django Validators
Validators can be used in Django in the models level or the level of the form. These validators are responsible for validating a field. The validators help to analyse the nature of the field with the value filled in the field. More importantly, these validators adjudicate the data being passed and post the errors onto the screen. This is the key benefit of Django validators. The Django validators can be done using methods such as clean() or even using field-level validators. It depends on the validator message used.
Syntax:
Raise validationerror(“”)
The process of raising a validation error is taken place through validators. This can be archived by means of the validation error exception, which can be raised at a form level and even at a field level. Here using this will raise the error and display it onto the console. The message which is expected to be raised has to be placed inbetween the double-quotes. The value between the double quotes will be displayed as the message associated to the error. Methods like clean() or even clean_fieldname can be used for raising these validation based errors. The validation errors can also be used to check all types of fields used across the forms section. The error message alerted onto the screen from the syntax will be very useful in determining the type of message being printed.
Create a Django Validator
Given below shows the creation of Django validator:
1. Changes in Models.py file
As mentioned in the syntax section, the email field needs to be declared in the models.py file. We can notice that the email field is declared as the age field in the model. Here the email field will be retrieved by default from the user table. The user table 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:
Code:
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
Ensure all the values and the database connects are set properly in the settings.py file to kick the project for execution flexibly. Furthermore, the middleware items mentioned below have to be declared properly in the settings.py file because these middle wares are responsible for the functioning of the application while processing GET and PUT messages. Additionally, the templates used has also need to fill so that the template processing happens in the background.
Settings.py:
Code:
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
The signup page needs to be added here; here, it’s added using the url function. The views.sign_up_request will get the sign page to be rendered when needed. The name associated to the page here is register. So this page will be helpful in getting the users registered.
url.py:
Code:
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/<str:pk>/',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/<str:pk>/',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 placed here at the NewuserForm. This form will act as a signup request, and here the validation values have been placed to check the email field to verify for good values, and if there are any unexpected values passed through the email field, then the error is raised.
Ex: views.py
Code:
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
Corresponding changes to the HTML pages have to be performed.
signuppage.html:
Code:
<!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 on in what way the email field can be docilely professed in a Django setup, and the variations can be rendered to an html page with validation errors getting populated onto the screen when a bad value has been placed.
Recommended Articles
This is a guide to Django Validators. Here we discuss the introduction and create a Django validator for better understanding. You may also have a look at the following articles to learn more –
2 Online Courses | 2 Hands-on Projects | 14+ Hours | Verifiable Certificate of Completion
4.5
View Course
Related Courses