User Authentication

24-Jan-2024

Implement secure user authentication in Django with our quick guide. Learn the essentials of creating a reliable and user-friendly authentication system for your web applications.

Introduction

Django offers a robust and integrated system for user authentication, encompassing key functionalities such as user registration, login, and logout. This comprehensive guide walks you through the fundamental aspects of incorporating user authentication into your Django application.



User Registration


  • Creating a Custom User Model :

    While Django provides a default user model, you have the flexibility to define a custom user model by extending AbstractUser to accommodate additional fields. Here's an example in your models.py :


    from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): bio = models.TextField(blank=True)


  • Designing a Registration Form :

    Utilize Django's built-in UserCreationForm to craft a registration form. Define the form in your forms.py :


    from django import forms from django.contrib.auth.forms import UserCreationForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email', 'password1', 'password2', 'bio')


  • Implementing the Registration View :

    Create a dedicated view for user registration, making use of the custom form :

    from django.shortcuts import render, redirect from django.contrib.auth import login from .forms import CustomUserCreationForm def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') else: form = CustomUserCreationForm() return render(request, 'registration/register.html', {'form': form})


  • Designing the Registration Template :

    Develop a template for user registration:

    <!-- registration/templates/registration/register.html -->
    
    {% extends 'base.html' %}

    {% block content %}
    <h2>User Registration</h2>
    <form method="post" action="{% url 'register' %}">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Register</button>
    </form>
    {% endblock %}
    
    



User Login

  • Crafting the Login View :

    Establish a view for user login :

    from django.contrib.auth.forms import AuthenticationForm
    from django.contrib.auth import authenticate, login
    
    def user_login(request):
        if request.method == 'POST':
            form = AuthenticationForm(request, request.POST)
            if form.is_valid():
                username = form.cleaned_data.get('username')
                password = form.cleaned_data.get('password')
                user = authenticate(username=username, password=password)
                if user:
                    login(request, user)
                    return redirect('home')
        else:
            form = AuthenticationForm()
    
        return render(request, 'registration/login.html', {'form': form})
    


  • Designing the Login Template :

    Craft a template for user login:

    <!-- registration/templates/registration/login.html -->
    
    
    {% extends 'base.html' %}
    
    {% block content %}
    
        <h2>User Login</h2>
        <form method='post' action="{% url 'user_login' %}"
    {% csrf_token %} {{ form.as_p }}
            <button type='submit'>Login</Button>
        </form>
    {% endblock %}





User Logout


  • Implementing the Logout View :

    Develop a view for user logout:

    from django.contrib.auth import logout
    
    def user_logout(request):
        logout(request)
        return redirect('home')
    
    

Comments