Authentication (Django)

Django's authentication system, in django.contrib.auth, handles users, passwords, login, and logout. It provides a User model, secure password hashing, login_required protection, and request.user for the current user.

Django

Authentication ships built in. The User model stores accounts with securely hashed passwords (Django never stores plaintext), and helper functions authenticate(), login(), and logout() manage sessions. After login, request.user is the logged-in User, or an AnonymousUser if not signed in.

You protect views with the @login_required decorator (or LoginRequiredMixin for class-based views), which redirects anonymous visitors to the login page. Django also provides ready-made auth views and forms for login, logout, and password reset that you wire into your URLs.

Most projects extend the default user — adding fields via a related Profile model or, better from the start, a custom user model (AUTH_USER_MODEL). Authentication (who you are) is distinct from permissions/authorization (what you may do).

Syntax

from django.contrib.auth import authenticate, login
login(request, user)

Examples

Python

from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required

def do_login(request):
    user = authenticate(request, username=u, password=p)
    if user is not None:
        login(request, user)

@login_required
def dashboard(request):
    return render(request, "dashboard.html")

Learn it in a lesson

See also

Back to the Dictionary