SyntaxStudy
Sign Up
Django Login, Logout, and Built-in Auth Views
Django Beginner 1 min read

Login, Logout, and Built-in Auth Views

Django's django.contrib.auth application provides a complete authentication system including a User model, password hashing, session management, and a set of built-in views for login, logout, password change, and password reset. Including django.contrib.auth.urls in your root URLconf adds all these views at once, requiring minimal custom code to get a working authentication system. The login view renders a login form and, on successful authentication, redirects to the URL specified in the LOGIN_REDIRECT_URL setting or a next parameter in the query string. The @login_required decorator and LoginRequiredMixin class redirect unauthenticated users to the login URL (LOGIN_URL setting). The logout view clears the session and redirects to LOGOUT_REDIRECT_URL. Django stores the authenticated user on the request object as request.user. For authenticated users this is a User instance; for unauthenticated users it is an AnonymousUser instance. The user is available in templates via the auth context processor as {{ user }}. Checking user.is_authenticated, user.is_staff, and user.has_perm() are the primary ways to conditionally render content based on the user's authentication state.
Example
# mysite/urls.py — include built-in auth URLs
from django.urls import path, include

urlpatterns = [
    # Provides: login, logout, password_change, password_reset, etc.
    path('accounts/', include('django.contrib.auth.urls')),
]

# mysite/settings.py — auth redirect settings
LOGIN_URL           = '/accounts/login/'
LOGIN_REDIRECT_URL  = '/blog/'
LOGOUT_REDIRECT_URL = '/accounts/login/'

# templates/registration/login.html — override the default login template
# {% extends "base.html" %}
# {% block content %}
# <form method="post">
#   {% csrf_token %}
#   {{ form.as_p }}
#   <button type="submit">Log In</button>
# </form>
# {% endblock %}

# blog/views.py — protecting a view
from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):
    posts = request.user.posts.all()
    return render(request, 'blog/dashboard.html', {'posts': posts})

# Template usage
# {% if user.is_authenticated %}
#   <p>Welcome, {{ user.username }}!</p>
#   <a href="{% url 'logout' %}">Log out</a>
# {% else %}
#   <a href="{% url 'login' %}">Log in</a>
# {% endif %}