Users Online

· Guests Online: 48

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Articles Hierarchy

Django Tutorial

Django Validators

Django Validators

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. The Django validators can be done using methods such as clean() or 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 using 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 on the console. The message that is expected to be raised must be placed between the double quotes. The value between the double quotes will be displayed as the message associated with the error. Methods like clean() or even clean_fieldname can raise these validation-based errors. The validation errors can also be used to check all fields 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 the 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:

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 connections are correctly set in the settings.py file to kick the project for execution flexibly. Furthermore, the middleware items mentioned below have to be appropriately declared in the settings.py file because these middlewares are responsible for the functioning of the application while processing 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

The signup page needs to be added here; here, it’s added using the URL function. The views.sign_up_request will render the sign page when needed. The name associated with the page here is registered. So this page will help get the users registered.

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 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.

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

Corresponding changes to the HTML pages have to be performed.

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:

Django Validators 1

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.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.80 seconds
10,842,345 unique visits