Django: signing in, signing out and protected pages

Lesson 7 of 9 · Python web: Django project

We do not write a view for signing in and out – Django has them ready (LoginView, LogoutView). It is enough to include their addresses and make a template. Then we lock the pages that only signed-in users may see.

Before you start: required prior knowledge – registration (SR).
How to learn: work in your own project step by step and after every lesson check that the server works; do the task at the end on your own first. The code is for Django 5.2 (LTS) and Python 3.12+; type each part into the file named in the comment at the top of the example.

Ready-made addresses for accounts

The line path("nalozi/", include("django.contrib.auth.urls")) in the main urls.py includes:

AddressRoute nameWhat it does
/nalozi/login/loginthe sign-in form
/nalozi/logout/logoutsigning out (POST only)
/nalozi/password_change/password_changechanging the password
/nalozi/password_reset/password_reseta forgotten password (requires sending email)

Where you go after signing in and out is set by LOGIN_REDIRECT_URL and LOGOUT_REDIRECT_URL from lesson 3; LOGIN_URL = "login" says where a user who is not signed in is sent. (nalozi = accounts – the name of the app in this project.)

The sign-in template

{# templates/registration/login.html – Django's LoginView looks for this name and place #}
{% extends "base.html" %}

{% block naslov %}Sign in – Logo Creator{% endblock %}

{% block sadrzaj %}
<div class="container py-4" style="max-width: 420px">
  <h1 class="h3 mb-3">Sign in</h1>
  {% if form.non_field_errors %}
    <div class="alert alert-danger">Wrong username or password.</div>
  {% endif %}
  <form method="post">
    {% csrf_token %}
    <div class="mb-3">
      <label for="id_username" class="form-label">Username</label>
      <input type="text" name="username" id="id_username" class="form-control" required autofocus>
    </div>
    <div class="mb-3">
      <label for="id_password" class="form-label">Password</label>
      <input type="password" name="password" id="id_password" class="form-control" required>
    </div>
    <input type="hidden" name="next" value="{{ next }}">
    <button class="btn btn-danger w-100">Sign in</button>
  </form>
  <p class="mt-3 small">No account? <a href="{% url 'registracija' %}">Register</a>.</p>
</div>
{% endblock %}

LoginView looks for the template registration/login.html and gives it the form under the name form and the return address next. If the data is wrong, form.non_field_errors is not empty. The message deliberately does not say whether the name or the password is wrong – that way an attacker cannot find out which usernames exist.

Signing out: why POST

Since Django 5.0, signing out works only with a POST request. If a link (GET) were enough, someone else's page could sign you out with a hidden image pointing to that address (CSRF). That is why signing out in base.html is a small form with a button:

<form method="post" action="{% url 'logout' %}" class="d-inline">
  {% csrf_token %}
  <button class="btn btn-link nav-link">Sign out ({{ user.username }})</button>
</form>

Old examples with <a href="/logout/"> return the error 405 (Method Not Allowed) in new versions.

Protected pages

from django.contrib.auth.decorators import login_required

@login_required                     # a user who is not signed in goes to /nalozi/login/?next=/moji-logoi/
def moji_logoi(request):
    logos = request.user.logoi.all()
    return render(request, "logoi/moji_logoi.html", {"logos": logos})
CheckWhereExample
@login_requiredviewthe whole page only for signed-in users
request.user.is_authenticatedviewthe same view works differently (generator: saving only for signed-in users)
{% if user.is_authenticated %}templatewhat is shown in the menu
get_object_or_404(..., vlasnik=request.user)viewa user gets only their own data (lesson 8)
Important: hiding a link in a template is not protection – anyone can type the address by hand. The view must always do the check as well.

Video: the sign-in page

Note on the video: the video is in Serbian and was recorded for the first version of the project (an older version of Django, Heroku). The ideas are the same, but the code from this lesson differs in details – when they differ, the code on this page applies.

In the video the sign-in view is written by hand (authenticate + login). That is good for understanding, but the ready-made LoginView is shorter and safer.

Practice tasks

Each task has an example, a hint and a solution.

TASK 01Difficulty: medium

A "My profile" page

Make a protected page /nalozi/profil/ that shows the username, the registration date, the number of saved logos and a link for changing the password.

Common mistakes and tips
  • The sign-in template must be exactly templates/registration/login.html.
  • Signing out with a link (GET) does not work in Django 5+ – use a form with POST.
  • Do not pass next on to other people's sites – Django's LoginView checks this itself, a view written by hand must check it too.

Check your knowledge

Open the quiz

Signing in and out

1. Why does signing out in Django 5 work only with a POST request?



2. What does @login_required do?




3. Is it enough to hide the link in the menu for a page to be protected?