How to Use Django’s Built-in Authentication System

Django is a high-level web framework that follows the Model-View-Controller (MVC) architectural pattern. One of the most useful features of Django is its built-in authentication system, which provides a secure way to handle user authentication and authorization. In this blog post, we’ll discuss how to use Django’s built-in authentication system.

Step 1: Create a Django Project

The first step is to create a new Django project. You can use the following command to create a new Django project:

django-admin startproject project_name

Step 2: Create a Django App

Next, you’ll need to create a new Django app inside your project. You can use the following command to create a new Django app:

python manage.py startapp app_name

Step 3: Configure Authentication Settings

Before we start using Django’s built-in authentication system, we need to configure some settings in the settings.py file of your project. Add the following code to the settings.py file:

AUTHENTICATION_BACKENDS = [

    ‘django.contrib.auth.backends.ModelBackend’,

    ‘allauth.account.auth_backends.AuthenticationBackend’,

]

AUTH_USER_MODEL = ‘app_name.CustomUser’

LOGIN_REDIRECT_URL = ‘/’

ACCOUNT_EMAIL_VERIFICATION = ‘none’

This code sets the authentication backends, specifies a custom user model, sets the redirect URL for login, and disables email verification.

Step 4: Create a Custom User Model

Now we need to create a custom user model that extends the default Django User model. To do this, create a new file called models.py in your app directory and add the following code:

from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):

    pass

Step 5: Create User Registration Views

In Django, a view is a Python function that takes a web request and returns a web response. We need to create two views for user registration, one for the registration form and one for the registration success page.

from django.shortcuts import render, redirect

from django.contrib.auth import authenticate, login

from .forms import RegistrationForm

def registration(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()

            username = form.cleaned_data.get(‘username’)

            password = form.cleaned_data.get(‘password’)

            user = authenticate(username=username, password=password)

            login(request, user)

            return redirect(‘success’)

    else:

        form = RegistrationForm()

    return render(request, ‘registration.html’, {‘form’: form})

def registration_success(request):

    return render(request, ‘registration_success.html’)

Step 6: Create Registration Forms

We need to create two forms for user registration, one for the registration form and one for the registration success page. Create a new file called forms.py in your app directory and add the following code:

from django import forms

from .models import CustomUser

class RegistrationForm(forms.ModelForm):

    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:

        model = CustomUser

        fields = [‘username’, ’email’, ‘password’]

Step 7: Create Login Views and Templates

In Django, we need to create two views for user login, one for the login form and one for the login success page.

from django.shortcuts import render, redirect

from django.contrib.auth import authenticate, login

def user_login(request):

    if request.method == ‘POST’:

        username = request.POST.get(‘username’)

        password = request.POST.get(‘password

Step 8: Create Login Forms

We also need to create a form for the user login. Create a new file called forms.py in your app directory and add the following code:

from django import forms

class LoginForm(forms.Form):

    username = forms.CharField()

    password = forms.CharField(widget=forms.PasswordInput)

Step 9: Create Logout View

To logout the user, create a logout view in your views.py file.

from django.contrib.auth import logout

def user_logout(request):

    logout(request)

    return redirect(‘home’)

Step 10: Add URLs to Your App

Add the URLs to your app by creating a new urls.py file in your app directory and adding the following code:

from django.urls import path

from . import views

urlpatterns = [

    path(‘register/’, views.registration, name=’register’),

    path(‘login/’, views.user_login, name=’login’),

    path(‘logout/’, views.user_logout, name=’logout’),

    path(‘success/’, views.registration_success, name=’success’),

]

Step 11: Create Templates

Create templates for the registration and login forms, as well as the registration and login success pages. Add these templates to your app’s templates directory.

registration.html:

{% extends ‘base.html’ %}

{% block content %}

    <h2>Register</h2>

    <form method=”POST”>

        {% csrf_token %}

        {{ form.as_p }}

        <button type=”submit”>Register</button>

    </form>

{% endblock %}

login.html:

{% extends ‘base.html’ %

Concusion: Django’s built-in authentication system provides a secure and easy way to handle user authentication and authorization in your web application. By following the steps outlined in this blog post, you can set up user registration, login, and logout functionality in your Django app using the built-in authentication system. Remember to customize your authentication settings and user model to fit your specific needs, and always prioritize security when working with user authentication. With these tips and best practices in mind, you can create a robust and secure authentication system for your Django web application.

If you’re looking to enhance your expertise in Django, LearnTube has got you covered with an array of online courses tailored to your needs. With the help of our specialized learning app and WhatsApp bot, you can enjoy a seamless learning experience. Our platform offers an extensive range of courses that cater to both novices and seasoned learners. For valuable insights, explore our diverse selection of courses on our website.

More from author

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Related posts

Advertismentspot_img

Latest posts

5 Fast-Track Data Science Courses for Engineers on a Budget

Data science has emerged as a critical skill for engineers looking to enhance their careers or transition into new roles. Engineers already have a...

Top 10 Intensive Data Science Courses for Quick Upskilling

In today’s rapidly evolving tech landscape, data science has become one of the most sought-after skills. Whether you’re a beginner or an experienced professional...

Top 10 Short Data Science Bootcamps for Quick Learning

Data science has become one of the most sought-after skills in today’s job market. For those looking to break into the field or upskill...

Want to stay up to date with the latest news?

We would love to hear from you! Please fill in your details and we will stay in touch. It's that simple!