Django: user registration

Lesson 6 of 9 · Python web: Django project

A user who wants to save logos creates an account. Django already has a user model, password hashing and a ready-made registration form (UserCreationForm) – we only write the view, the address and the template in the nalozi (accounts) app.

Before you start: required prior knowledge – models and the database (SR), HTML forms.
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.

How a form works in Django

GET  /nalozi/registracija/  → an empty form
POST /nalozi/registracija/  → a form with data
        │
        ├─ is_valid() = False → the same page, with error messages
        └─ is_valid() = True  → save() → login() → redirect to /moji-logoi/

The same pattern (GET shows, POST handles, a successful POST redirects) is used in every Django form. The redirect after POST prevents a page refresh from sending the form again.

The view and the address

# nalozi/views.py
from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import redirect, render


def registracija(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()                      # Django hashes the password itself
            login(request, user)                    # and signs the user in right away
            messages.success(request, f"Welcome, {user.username}!")
            return redirect("moji_logoi")
    else:
        form = UserCreationForm()
    return render(request, "nalozi/registracija.html", {"form": form})
# nalozi/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("registracija/", views.registracija, name="registracija"),
]

In the main urls.py uncomment the line path("nalozi/", include("nalozi.urls")). The registration address is /nalozi/registracija/.

PartWhat it does
UserCreationFormfields: username, password, password confirmation; it checks whether the name exists, whether the passwords match and whether the password is strong enough
form.save()creates the user; the password is stored as a hash (PBKDF2 – the same procedure as in the lesson Security)
login(request, user)creates a session – the user is signed in right away
messages.successa one-time message that base.html shows on the next page

A template with Bootstrap fields

{# nalozi/templates/nalozi/registracija.html #}
{% extends "base.html" %}

{% block naslov %}Registration – Logo Creator{% endblock %}

{% block sadrzaj %}
<div class="container py-4" style="max-width: 480px">
  <h1 class="h3 mb-3">Registration</h1>
  <form method="post" novalidate>
    {% csrf_token %}
    {% for field in form %}
      <div class="mb-3">
        <label for="{{ field.id_for_label }}" class="form-label">{{ field.label }}</label>
        <input type="{{ field.field.widget.input_type }}" name="{{ field.html_name }}" id="{{ field.id_for_label }}"
               class="form-control{% if field.errors %} is-invalid{% endif %}"
               {% if field.field.widget.input_type != "password" %}value="{{ field.value|default_if_none:'' }}"{% endif %}>
        {% for error in field.errors %}<div class="invalid-feedback">{{ error }}</div>{% endfor %}
        {% if field.help_text %}<div class="form-text">{{ field.help_text|safe }}</div>{% endif %}
      </div>
    {% endfor %}
    <button class="btn btn-danger w-100">Create an account</button>
  </form>
  <p class="mt-3 small">Already have an account? <a href="{% url 'login' %}">Sign in</a>.</p>
</div>
{% endblock %}

The loop {% for field in form %} prints all the fields with their label, errors and help text (the password rules). The class is-invalid colours a field red when it has an error. The attribute novalidate turns off the check in the browser, so that you see the messages returned by Django – useful while you are learning.

A faster way without customising the look: {{ form.as_div }} instead of the whole loop.

Try it

  1. Open /nalozi/registracija/ and send an empty form – error messages appear (in English, because of LANGUAGE_CODE = "en-us").
  2. Try the password 12345678 – Django rejects it as too common and entirely numeric.
  3. Create an account with a strong password – you will be redirected to /moji-logoi/ (that page is made in lesson 8; until then temporarily redirect to naslovna).
  4. In the admin panel look at the new user: the password is shown only as pbkdf2_sha256$... – a hash, not the real password.

Video: the registration module

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.

Practice tasks

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

TASK 01Difficulty: medium

Registration with email

Make a form RegistrationForm that inherits UserCreationForm and adds a required email field, and use it in the view instead of UserCreationForm.

Common mistakes and tips
  • Without {% csrf_token %} a POST form returns the error 403 (CSRF verification failed).
  • Never store passwords as text in your own model – use Django's user model.
  • After a successful POST always redirect, not render.

Check your knowledge

Open the quiz

Registration

1. What does Django store in the database instead of the password?




2. What should you do after a successfully handled POST form?



3. Which tag must be in every POST form in a Django template?