Django includes a complete authentication system: the User model, login/logout, and permissions.
User Model
from django.contrib.auth.models import User
# Creating
user = User.objects.create_user(
username='alice',
email='alice@example.com',
password='secret123'
)
# Retrieving
user = User.objects.get(username='alice')
print(user.username, user.email, user.is_staff, user.is_superuser)
Connecting Authentication URLs
# mysite/urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('accounts/', include('django.contrib.auth.urls')),
# Provides:
# /accounts/login/ → auth_views.LoginView
# /accounts/logout/ → auth_views.LogoutView
# /accounts/password_change/ and more
]
Login Page
A registration/login.html template is required:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Log in</button>
</form>
In settings.py:
LOGIN_REDIRECT_URL = '/' # redirect destination after login
LOGOUT_REDIRECT_URL = '/accounts/login/'
LOGIN_URL = '/accounts/login/' # redirect destination when not authenticated
Registration
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
login / logout in Code
from django.contrib.auth import login, logout, authenticate
# Authenticate and log in
user = authenticate(request, username='alice', password='secret123')
if user:
login(request, user)
# Log out
logout(request)
Checking in a Template
{% if user.is_authenticated %}
<p>Hello, {{ user.username }}!</p>
<a href="{% url 'logout' %}">Log out</a>
{% else %}
<a href="{% url 'login' %}">Log in</a>
{% endif %}
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!