Django
Beginner
1 min read
Login, Logout, and Built-in Auth Views
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 %}
Related Resources
Django Reference
Complete tag & property list
Django How-To Guides
Step-by-step practical guides
Django Exercises
Practice what you've learned
More in Django