Debug School

rakesh kumar
rakesh kumar

Posted on

How to apply validation during authentication in django

Apply custom Validation during custom authentication

Define the User model.
Open myapp/ and define a custom User model, if needed. Django provides a built-in User model that can be used for authentication. If you want to extend the User model, you can create a custom model by subclassing AbstractBaseUser or AbstractUser.

Create a form for login and registration in your file:

from django import forms

class LoginForm(forms.Form):
    username = forms.CharField(max_length=150)
    password = forms.CharField(widget=forms.PasswordInput)

class RegistrationForm(forms.Form):
    username = forms.CharField(max_length=150)
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)
    email = forms.EmailField()
    age = forms.IntegerField()
    agree_terms = forms.BooleanField()

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')

        if password and confirm_password and password != confirm_password:
            self.add_error('confirm_password', "Passwords do not match.")

        age = cleaned_data.get('age')
        if age and age < 18:
            self.add_error('age', "You must be at least 18 years old.")

        agree_terms = cleaned_data.get('agree_terms')
        if not agree_terms:
            self.add_error('agree_terms', "You must agree to the terms and conditions.")
Enter fullscreen mode Exit fullscreen mode

Image description

Create view functions for login and registration in your file:

from django.shortcuts import render, redirect
from .forms import LoginForm, RegistrationForm

def login_view(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            # Perform login logic
            return redirect('home')
        form = LoginForm()

    return render(request, 'login.html', {'form': form})

def registration_view(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            # Perform registration logic
            return redirect('login')
        form = RegistrationForm()

    return render(request, 'registration.html', {'form': form})
Enter fullscreen mode Exit fullscreen mode

Create corresponding HTML templates login.html and registration.html in your templates directory. Here's an example of login.html:

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Login</button>
Enter fullscreen mode Exit fullscreen mode

And an example of registration.html:

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Register</button>
Enter fullscreen mode Exit fullscreen mode

Define the URL patterns in your file:

from django.urls import path
from . import views

urlpatterns = [
    path('login/', views.login_view, name='login'),
    path('registration/', views.registration_view, name='registration'),
Enter fullscreen mode Exit fullscreen mode

With the above code, the RegistrationForm handles six different types of validations:

Password matching validation: The form checks if the password and confirm password fields have the same value.
Email validation: The form checks if the email field contains a valid email address.
Age validation: The form checks if the age field is provided and the user is at least 18 years old.
Agreement validation: The form checks if the agree_terms field is checked.
Required field validation: All fields are required by default, so the form will display errors if any required field is not provided.
CSRF protection: The form automatically includes a CSRF token to protect against CSRF attacks.

Top comments (0)