📝 Django

Authentication in Django

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
77
🌿
Level
Medium

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 %}

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 138
📝

JWT Tokens with python-jose

python-jose is a library for working with JSON Web Tokens (JWT).

📅 30.06.2026 👁️ 112
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 85

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!