Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Auth Application Implements User Authentication

In this tutorial, we'll cover how to implement user authentication in your Django application using the built-in Django authentication app.

Prerequisites:

  • Basic knowledge of Python
  • Familiarity with Django framework
  • A Django project set up and running

Step 1: Set up Django authentication

1.1. Install the necessary packages, if not already done:

pip install django

1.2. Create a new Django project and app, if you haven't already:

django-admin startproject myproject
cd myproject
python manage.py startapp myapp

1.3. Enable the authentication middleware in your project settings. Open myproject/settings.py and make sure 'django.contrib.auth.middleware.AuthenticationMiddleware' is included in the MIDDLEWARE list.

Step 2: Configure Django authentication

2.1. In myproject/settings.py, make sure the following apps are included in the INSTALLED_APPS list:

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

2.2. Add a login URL and login redirect URL to myproject/settings.py:

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'

Step 3: Implement authentication views

3.1. Create a view for user registration in myapp/views.py:

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from django.shortcuts import render, redirect

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('home')
    else:
        form = UserCreationForm()
    return render(request, 'myapp/register.html', {'form': form})

3.2. Create a view for the home page (where users will be redirected after login) in myapp/views.py:

from django.shortcuts import render

def home(request):
    return render(request, 'myapp/home.html')

Step 4: Implement authentication templates

4.1. Create a template for user registration in myapp/templates/myapp/register.html:

{% extends "myapp/base.html" %}

{% block content %}
  <h2>Register</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Register</button>
  </form>
{% endblock %}

4.2. Create a template for the home page in myapp/templates/myapp/home.html:

{% extends "myapp/base.html" %}

{% block content %}
  <h2>Welcome, {{ user.username }}!</h2>
{% endblock %}

4.3. Create a base template for your application in myapp/templates/myapp/base.html:

<!DOCTYPE html>
<html>
<head>
  <title>My Django App</title>
</head>
<body>
  <div>
    {% if user.is_authenticated %}
      <p>Welcome, {{ user.username }}! <a href="{% url 'logout' %}">Logout</a></p>
    {% else %}
      <p><a href="{% url 'login' %}">Login</a> | <a href="{% url 'register' %}">Register</a></p>
    {% endif %}
  </div>
  {% block content %}
  {% endblock %}
</body>
</html>
  1. Django login view and authentication backend: Django's login view (django.contrib.auth.views.LoginView) uses an authentication backend to verify user credentials. You can customize the authentication backend for advanced scenarios.

    # urls.py
    from django.contrib.auth.views import LoginView
    
    urlpatterns = [
        path('login/', LoginView.as_view(), name='login'),
    ]
    
  2. Django authentication forms in auth app: Django provides authentication forms (django.contrib.auth.forms) for handling login, password reset, and other authentication-related tasks.

    # forms.py
    from django import forms
    from django.contrib.auth.forms import AuthenticationForm
    
    class CustomAuthenticationForm(AuthenticationForm):
        # Customizations here
    
  3. User registration in Django auth application: While Django's auth app focuses on authentication, user registration involves creating a custom form and view for user creation.

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