Authentication in Django: A Beginner's Guide 🎯

beginner
22 min

Authentication in Django: A Beginner's Guide 🎯

Welcome to this comprehensive guide on Authentication in Django! This tutorial is designed to help you understand the essentials of user authentication in Django, a powerful Python web framework. πŸ“

By the end of this guide, you'll be able to create secure login and registration systems, protected views, and manage user sessions. Let's dive in! πŸ€–

Table of Contents πŸ“

  1. Introduction to Authentication in Django
  2. Setting Up a Django Project
  3. Creating User Models
  4. Creating Login and Registration Views
  5. Protecting Views with User Authentication
  6. User Session Management
  7. Quiz: Test Your Knowledge

1. Introduction to Authentication in Django πŸ“

Authentication is the process of verifying a user's identity before granting them access to protected resources. In Django, this is handled by the built-in django.contrib.auth module.


2. Setting Up a Django Project πŸ“

To get started, you'll need to have Python and Django installed on your system. Once that's done, create a new Django project:

bash
django-admin startproject django_auth cd django_auth

3. Creating User Models πŸ“

Django comes with a built-in User model, but for this tutorial, we'll create a custom User model:

bash
python manage.py startapp users

In the users/models.py, define your custom User model:

python
from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass

Remember to update the AUTH_USER_MODEL setting in settings.py to point to your custom User model:

python
AUTH_USER_MODEL = 'users.CustomUser'

4. Creating Login and Registration Views πŸ“

Next, we'll create login and registration views using Django's built-in LoginView and CreateUserView:

bash
pip install django-crispy-forms

Add 'crispy_forms' to your INSTALLED_APPS in settings.py.

In your users/views.py, create the following views:

python
from django.contrib.auth import login, logout from django.contrib.auth.views import LoginView, LogoutView, PasswordResetView from django.contrib.auth.forms import PasswordResetForm from django.urls import path from django.views.generic import CreateView from django.contrib.auth.forms import UserCreationForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class CustomLoginView(LoginView): # ... class CustomLogoutView(LogoutView): # ... class RegisterView(CreateView): model = CustomUser form_class = UserCreationForm success_url = '/' template_name = 'users/register.html' class PasswordResetViewCustom(PasswordResetView): form_class = PasswordResetForm template_name = 'users/password_reset.html' urlpatterns = [ # ... path('accounts/login/', CustomLoginView.as_view(), name='login'), path('accounts/logout/', CustomLogoutView.as_view(), name='logout'), path('accounts/register/', RegisterView.as_view(), name='register'), path('accounts/password_reset/', PasswordResetViewCustom.as_view(), name='password_reset'), # ... ]

5. Protecting Views with User Authentication πŸ“

Now, let's protect a view so it can only be accessed by authenticated users:

python
from django.contrib.auth.decorators import login_required @login_required def protected_view(request): # ... urlpatterns = [ # ... path('protected/', protected_view, name='protected'), # ... ]

6. User Session Management πŸ“

Django takes care of user sessions automatically. You can get, set, and delete session data as needed:

python
from django.http import HttpResponse def set_session(request): request.session['key'] = 'value' return HttpResponse('Session data set') def get_session(request): value = request.session.get('key') return HttpResponse(f'Session data: {value}') def delete_session(request): del request.session['key'] return HttpResponse('Session data deleted')

7. Quiz: Test Your Knowledge 🎯

Quick Quiz
Question 1 of 1

Which Django module handles user authentication?