Python > Web Development with Python > Django > Authentication and Authorization

Django User Authentication with Built-in Forms

This snippet demonstrates how to use Django's built-in authentication forms (UserCreationForm and AuthenticationForm) for user registration and login. It provides a basic setup for handling user authentication within a Django project, including form rendering in templates and view logic for processing form submissions.

Concepts Behind the Snippet

This snippet leverages Django's built-in authentication system, which provides pre-built forms and views for common authentication tasks. The UserCreationForm simplifies user registration, handling password hashing and user creation in the database. The AuthenticationForm handles user login, validating credentials against the database. Using these built-in components significantly reduces the amount of custom code required for authentication.

Creating a Django Project and App

First, create a Django project and an app for authentication. If you already have a project, you can skip project creation. We'll call our app 'accounts'.

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

urls.py Configuration (Project Level)

Include the app's URLs in the project's urls.py file.

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls')),
]

urls.py Configuration (App Level - accounts)

Create a urls.py file inside the 'accounts' app to define the URL patterns for registration and login views.

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'),
]

Views for Registration and Login (views.py in accounts app)

Implement the views for registration and login using Django's built-in forms.

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

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

def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('home') # Redirect to your home page
    else:
        form = AuthenticationForm()
    return render(request, 'accounts/login.html', {'form': form})

def logout_view(request):
    logout(request)
    return redirect('home') # Redirect to your home page

Templates (register.html and login.html in accounts/templates/accounts/)

Create simple templates to render the forms. Make sure your template directory structure is correct (accounts/templates/accounts/).

{% extends 'base.html' %} {# Create base.html with basic HTML structure #}

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


{% extends 'base.html' %}

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

Real-Life Use Case

This is a standard setup for creating user accounts and authenticating users on any Django-based web application. It is used in e-commerce sites, social media platforms, and content management systems to manage user access and personalize the user experience. You would extend this by adding user profile information, password reset functionality, and potentially social authentication (e.g., login with Google/Facebook).

Best Practices

  • Use HTTPS: Always serve your website over HTTPS to protect user credentials during transmission.
  • Password Strength: Consider using Django's built-in password validators or installing third-party libraries to enforce strong password policies.
  • CSRF Protection: Ensure that CSRF (Cross-Site Request Forgery) protection is enabled in your forms and views (as shown with {% csrf_token %}).
  • Input Validation: Leverage Django's form validation to sanitize user inputs and prevent vulnerabilities like SQL injection.
  • Rate Limiting: Implement rate limiting to prevent brute-force attacks on login forms.

Interview Tip

Be prepared to discuss the security implications of authentication and authorization. Understand the differences between authentication (verifying identity) and authorization (granting access to resources). Know how Django's authentication system works under the hood, including the role of middleware and the User model.

When to Use Them

Use Django's built-in authentication forms for basic user registration and login scenarios. If you require highly customized authentication flows or integrations with external authentication providers (e.g., OAuth), consider using custom forms and views or third-party packages like django-allauth.

Alternatives

  • django-allauth: Provides social authentication (Google, Facebook, etc.) and more advanced authentication features.
  • django-rest-framework-simplejwt: For token-based authentication in REST APIs.
  • Custom Authentication Backends: Allows you to authenticate users against different data sources (e.g., LDAP, Active Directory).

Logout functionality

Don't forget to create a logout view and include it in your urls.py. The user experience is drastically improved if a logout option is available.

from django.shortcuts import redirect
from django.contrib.auth import logout

def logout_view(request):
    logout(request)
    return redirect('home') # Redirect to your home page

FAQ

  • Why am I getting a CSRF token missing or incorrect error?

    This error occurs when the CSRF (Cross-Site Request Forgery) protection is enabled, but the CSRF token is not present in the form or is not being passed correctly. Ensure you have {% csrf_token %} within your form in the template, and that the 'django.middleware.csrf.CsrfViewMiddleware' middleware is enabled in your settings.py file.
  • How do I redirect users after login/registration?

    Use the redirect() function from django.shortcuts to redirect users to a specific URL after successful login or registration. You can redirect them to a home page, their profile page, or any other relevant page within your application. Use the reverse() function if you want to redirect by URL name instead of hardcoding the URL.