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

Top AWS Interview Questions & Answers 2024

If you've ever wanted to work in the cloud industry, now is your chance. With cloud computing platforms like Amazon Web Services (AWS) sweeping...

How Much Will I Earn as a Flutter Developer? The Ultimate Salary Guide for 2024

Flutter is a popular cross-platform mobile app development framework that is gaining immense popularity among developers worldwide. As the demand for Flutter developers continues...

Top Companies Hiring Flutter Developers in 2024

As the popularity of Flutter continues to rise, there is a growing demand for skilled Flutter developers in various industries. In 2024, there will...

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!