Django Authentication System

## Introduction to Django Authentication System
Django comes with a built-in authentication system that provides a lot of functionality out of the box. It includes user authentication, permission management, and session management. In this tutorial, we will explore how to use Django’s authentication system to create a basic login and registration system.

## Setting Up the Authentication System
To start using the authentication system, you need to make sure it is installed. The authentication system is included in the Django framework by default, but you need to add ‘django.contrib.auth’ and ‘django.contrib.contenttypes’ to your INSTALLED_APPS in your settings.py file. Here is how you can do it:


INSTALLED_APPS = [
    # ...
    'django.contrib.auth',
    'django.contrib.contenttypes',
    # ...
]

## Creating a User Model
Django comes with a built-in User model, but you can also create your own custom User model. To create a custom User model, you need to create a new model that inherits from AbstractBaseUser. Here is an example of how you can create a custom User model:


from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models

class CustomUserManager(BaseUserManager):
    def create_user(self, email, password=None):
        if not email:
            raise ValueError('Users must have an email address')
        user = self.model(email=self.normalize_email(email))
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password=None):
        user = self.create_user(email, password=password)
        user.is_admin = True
        user.save(using=self._db)
        return user

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    objects = CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

## Creating Forms for User Registration and Login
To create forms for user registration and login, you can use Django’s built-in forms. Here is an example of how you can create forms for user registration and login:


from django import forms
from .models import CustomUser

class RegistrationForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = CustomUser
        fields = ('email',)

    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:
            raise forms.ValidationError('Passwords do not match')

class LoginForm(forms.Form):
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)

## Creating Views for User Registration and Login
To create views for user registration and login, you can use Django’s built-in views. Here is an example of how you can create views for user registration and login:


from django.shortcuts import redirect, render
from django.contrib.auth import authenticate, login, logout
from .forms import RegistrationForm, LoginForm

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data['password'])
            user.save()
            return redirect('login')
    else:
        form = RegistrationForm()
    return render(request, 'register.html', {'form': form})

def login_view(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            user = authenticate(email=email, password=password)
            if user is not None:
                login(request, user)
                return redirect('home')
    else:
        form = LoginForm()
    return render(request, 'login.html', {'form': form})

## Creating URLs for User Registration and Login
To create URLs for user registration and login, you can use Django’s built-in URL dispatcher. Here is an example of how you can create URLs for user registration and login:


from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.register, name='register'),
    path('login/', views.login_view, name='login'),
    path('logout/', views.logout_view, name='logout'),
]

## Conclusion
In this tutorial, we have explored how to use Django’s authentication system to create a basic login and registration system. We have created a custom User model, forms for user registration and login, views for user registration and login, and URLs for user registration and login. With this knowledge, you can create your own authentication system in Django. Remember to always follow best practices for security and authentication.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *