Working with Django's Built-in Authentication System

Django provides a robust built-in authentication framework that handles user registration, login, logout, password management, and access control.

To begin, create an admin user via the command line:

python manage.py createsuperuser

The core functionality is accessible through django.contrib.auth.

User Authentication

The authenticate() function validates credentials:

from django.contrib import auth

user = auth.authenticate(username=input_user, password=input_pass)
if user is not None:
    # Credentials are valid
    print(user.username)
else:
    # Invalid login
    pass

Note: Passwords are stored as hashed values, not plaintext.

Session Managmeent

After successful authentication, persist the session using login():

auth.login(request, user)  # Binds user to request.session

Before login, request.user returns an AnonymousUser; afterward, it holds the authenticated User instance. This is enabled by Django’s authentication middleware.

To log a user out and clear their session:

def sign_out(request):
    auth.logout(request)

This safely handles cases where the user isn’t logged in.

Access Control

Check if a user is authenticated:

if request.user.is_authenticated:
    # Proceed with protected logic
    pass

Enforce login requirements on views using the @login_required decorator:

from django.contrib.auth.decorators import login_required

@login_required(login_url='/signin/')
def dashboard(request):
    return render(request, 'dashboard.html')

Unauthenticated users are redirected to the specified URL with a ?next= query parameter indicating their original destination. The default redirect URL (/accounts/login/) can be overridden globally in settings.py:

LOGIN_URL = '/signin/'

User Creation and Password Handling

Create regular or superusers programmatically:

from django.contrib.auth.models import User

# Standard user
regular = User.objects.create_user(
    username='alice',
    password='secure123',
    email='alice@example.com'
)

# Superuser (email required)
superuser = User.objects.create_superuser(
    username='admin',
    password='admin123',
    email='admin@example.com'
)

Avoid User.objects.create()—it stores passowrds in plaintext and bypasses hashing.

Verify or update passwords securely:

# Verify
if request.user.check_password('candidate_pass'):
    # Password matches

# Change password
request.user.set_password('new_secure_pass')
request.user.save()  # Required to persist change

Key User Attributes

  • username: Unique identifier
  • password: Hashed credential
  • is_staff: Grants access to the admin interface
  • is_active: Controls login eligibility without deleting the account

Customizing the User Model

For extended user profiles, subclass AbstractUser:

from django.contrib.auth.models import AbstractUser
from django.db import models

class Profile(AbstractUser):
    phone = models.CharField(max_length=11, unique=True, null=True)
    
    def __str__(self):
        return self.username

Register the custom model in settings.py:

AUTH_USER_MODEL = 'myapp.Profile'

Important: Changing AUTH_USER_MODEL requires recreating the database schema from scratch, as Django ties this setting to initial migrations.

Tags: Django Authentication User Management web development python

Posted on Thu, 14 May 2026 02:39:45 +0000 by justinwhite93