Skip to main content

Web frameworks · Intermediate · 28 min

Add sign-up, login and password reset to a Django app

By Padding · Updated 18 Nov 2026
Django 6.1 · Python 3.15 (python:3.15-slim)

You will have a Django 6.1 notes app with a custom user model, sign-up, login, logout and a working password reset, where each user sees only their own notes and a test suite proves it.

On this page

Most apps reach the same point early: people need accounts, and each person's data has to stay theirs. Django already ships the hard parts in django.contrib.auth: password hashing, sessions, login and logout views, and a password reset flow with signed, expiring links. Your job is to wire them up, give them templates, and make every view check who is asking.

In this tutorial you build a small notes app. A visitor signs up, lands on their own notes, adds and deletes notes, logs out, and can reset a forgotten password through an emailed link. During development, Django prints that email in the server terminal instead of sending it. You finish with tests that prove one user cannot see or delete another user's notes.

It builds on your first Django 6 app, so uv, manage.py and the development server should already be familiar.

Step 1 · Start the project with a custom user model

Create the project and add Django, kept within the 6.1 series:

Bash
mkdir -p ~/notes-auth-demo
cd ~/notes-auth-demo
uv init --no-package
rm main.py
uv add "django>=6.1,<6.2"
uv run django-admin startproject config .
uv run python manage.py startapp accounts
uv run python manage.py startapp notes

Before you run migrate for the first time, decide what your user model is. Django's built-in auth.User works, but other tables point at it with foreign keys from the first migration onwards. Swapping it for your own model later means rewriting those relationships by hand on a live database, which the Django documentation itself describes as significantly more difficult. A custom model that starts out identical to the built-in one costs four lines today and leaves room for a phone number, a display name or a preferred language later.

Write the model in accounts/models.py:

Bash
cat > accounts/models.py <<'PY'
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    """Same fields as Django's default user. Add your own here later."""
PY

Register it in the admin, using Django's ready-made user admin screens:

Bash
cat > accounts/admin.py <<'PY'
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .models import User

admin.site.register(User, UserAdmin)
PY

Now tell Django about the two apps and the user model. Append these lines to the end of config/settings.py rather than editing the generated text. accounts goes first in INSTALLED_APPS because the admin app ships its own registration/ templates, and Django uses the first match it finds:

Bash
cat >> config/settings.py <<'PY'

# Authentication
INSTALLED_APPS = ["accounts", "notes", *INSTALLED_APPS]
AUTH_USER_MODEL = "accounts.User"
LOGIN_REDIRECT_URL = "notes:list"
LOGOUT_REDIRECT_URL = "login"
PY

Create the first migration for accounts, then build the database:

Bash
uv run python manage.py makemigrations accounts
uv run python manage.py migrate

Check it worked

makemigrations prints + Create model User under accounts/migrations/0001_initial.py. migrate applies accounts.0001_initial alongside Django's own migrations and ends without errors. If the checks report that a reverse accessor for accounts.User.groups clashes with one for auth.User.groups, the AUTH_USER_MODEL line is missing from the settings.

Step 2 · Wire up the built-in login and logout views

django.contrib.auth.urls gives you a set of named URLs in one line: login, logout, password_change, password_reset and the steps that follow it. Replace config/urls.py. Your own accounts URLs come first, so they sit next to Django's under /accounts/:

Bash
cat > config/urls.py <<'PY'
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("accounts.urls")),
    path("accounts/", include("django.contrib.auth.urls")),
    path("", include("notes.urls")),
]
PY

The views exist, but they need templates. Start with a base layout that every page extends. It shows who is signed in, and logs out through a form: since Django 5.0 the logout view only accepts POST, so a link that a crawler or a prefetching browser follows cannot sign anyone out.

Bash
mkdir -p accounts/templates/registration
cat > accounts/templates/base.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{% block title %}Notes{% endblock %}</title>
</head>
<body>
  <header>
    {% if user.is_authenticated %}
      <p>Signed in as {{ user.username }}</p>
      <form method="post" action="{% url 'logout' %}">
        {% csrf_token %}
        <button type="submit">Log out</button>
      </form>
    {% else %}
      <p><a href="{% url 'login' %}">Log in</a> or <a href="{% url 'sign_up' %}">sign up</a></p>
    {% endif %}
  </header>
  <main>
    {% block content %}{% endblock %}
  </main>
</body>
</html>
HTML

The login view looks for registration/login.html and passes it a form and a next value, the page to return to after logging in:

Bash
cat > accounts/templates/registration/login.html <<'HTML'
{% extends "base.html" %}
{% block title %}Log in{% endblock %}
{% block content %}
  <h1>Log in</h1>
  <form method="post">
    {% csrf_token %}
    {{ form.as_div }}
    <input type="hidden" name="next" value="{{ next }}">
    <button type="submit">Log in</button>
  </form>
  <p><a href="{% url 'password_reset' %}">Forgotten your password?</a></p>
{% endblock %}
HTML

The base template links to a sign_up URL that does not exist yet. You add it in the next step, so leave the server off for now.

Check it worked

ls accounts/templates/registration lists login.html, and accounts/templates/base.html exists. You start the server and look at the page once the sign-up URL is in place.

Step 3 · Add a sign-up page

Django has no sign-up view, but it has the form: UserCreationForm checks that the username is free, that both passwords match, and runs them through the password validators in AUTH_PASSWORD_VALIDATORS. Out of the box it targets the built-in auth.User, so point a subclass at your model and ask for an email address, which the password reset needs:

Bash
cat > accounts/forms.py <<'PY'
from django import forms
from django.contrib.auth.forms import UserCreationForm

from .models import User


class SignUpForm(UserCreationForm):
    email = forms.EmailField(required=True, help_text="Used only to reset your password.")

    class Meta(UserCreationForm.Meta):
        model = User
        fields = ("username", "email")
PY

The view saves the user and logs them straight in, so a new member does not have to type their password twice in a row:

Bash
cat > accounts/views.py <<'PY'
from django.contrib.auth import login
from django.shortcuts import redirect, render

from .forms import SignUpForm


def sign_up(request):
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect("notes:list")
    else:
        form = SignUpForm()
    return render(request, "registration/sign_up.html", {"form": form})
PY

cat > accounts/urls.py <<'PY'
from django.urls import path

from . import views

urlpatterns = [
    path("sign-up/", views.sign_up, name="sign_up"),
]
PY

cat > accounts/templates/registration/sign_up.html <<'HTML'
{% extends "base.html" %}
{% block title %}Sign up{% endblock %}
{% block content %}
  <h1>Create an account</h1>
  <form method="post">
    {% csrf_token %}
    {{ form.as_div }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}
HTML

The default username field accepts letters from any script, plus digits and @ . + - _, so members can sign up with names written in Amharic, Arabic or Hausa without extra work. Keep error messages short and the pages light: these forms are often filled in on a low-end Android phone over prepaid data.

Check it worked

accounts/forms.py, accounts/views.py, accounts/urls.py and accounts/templates/registration/sign_up.html all exist. The project still needs the notes URLs that config/urls.py includes, which come next.

Step 4 · Keep each user's notes private

A note belongs to one user. Point the foreign key at settings.AUTH_USER_MODEL, never at a user class directly, so the code keeps working whatever the user model is:

Bash
cat > notes/models.py <<'PY'
from django.conf import settings
from django.db import models


class Note(models.Model):
    owner = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notes"
    )
    text = models.CharField(max_length=500)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created", "-id"]

    def __str__(self):
        return self.text
PY

The views use both styles of protection Django offers. @login_required wraps a function view, and LoginRequiredMixin goes first in a class-based view's parents. Either one sends an anonymous visitor to the login page with ?next= set to where they were going. Logging in is only half the job, though: every query also filters on owner, so a signed-in user who guesses another note's ID gets a 404, not the note.

Bash
cat > notes/views.py <<'PY'
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView, DeleteView

from .models import Note


@login_required
def note_list(request):
    return render(request, "notes/list.html", {"notes": request.user.notes.all()})


class NoteCreate(LoginRequiredMixin, CreateView):
    model = Note
    fields = ["text"]
    success_url = reverse_lazy("notes:list")

    def form_valid(self, form):
        form.instance.owner = self.request.user
        return super().form_valid(form)


class NoteDelete(LoginRequiredMixin, DeleteView):
    http_method_names = ["post"]
    success_url = reverse_lazy("notes:list")

    def get_queryset(self):
        return Note.objects.filter(owner=self.request.user)
PY

cat > notes/urls.py <<'PY'
from django.urls import path

from . import views

app_name = "notes"
urlpatterns = [
    path("", views.note_list, name="list"),
    path("new/", views.NoteCreate.as_view(), name="create"),
    path("<int:pk>/delete/", views.NoteDelete.as_view(), name="delete"),
]
PY

Add the two templates. CreateView looks for notes/note_form.html by default:

Bash
mkdir -p notes/templates/notes
cat > notes/templates/notes/list.html <<'HTML'
{% extends "base.html" %}
{% block title %}My notes{% endblock %}
{% block content %}
  <h1>My notes</h1>
  <p><a href="{% url 'notes:create' %}">New note</a></p>
  <ul>
    {% for note in notes %}
      <li>
        {{ note.text }}
        <form method="post" action="{% url 'notes:delete' note.pk %}">
          {% csrf_token %}
          <button type="submit">Delete</button>
        </form>
      </li>
    {% empty %}
      <li>No notes yet.</li>
    {% endfor %}
  </ul>
{% endblock %}
HTML

cat > notes/templates/notes/note_form.html <<'HTML'
{% extends "base.html" %}
{% block title %}New note{% endblock %}
{% block content %}
  <h1>New note</h1>
  <form method="post">
    {% csrf_token %}
    {{ form.as_div }}
    <button type="submit">Save</button>
  </form>
{% endblock %}
HTML

Create the table, then start the development server in a second terminal and leave it running:

Bash
uv run python manage.py makemigrations notes
uv run python manage.py migrate
Bash
uv run python manage.py runserver

Ask for the notes page without being logged in, and look at where Django sends you:

Bash
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://127.0.0.1:8000/
curl -s http://127.0.0.1:8000/accounts/sign-up/ | grep -o '<h1>[^<]*</h1>'

Check it worked

The first command prints 302 http://127.0.0.1:8000/accounts/login/?next=/: the notes page refuses anonymous visitors. The second prints <h1>Create an account</h1>. In a browser, open http://127.0.0.1:8000/accounts/sign-up/, create an account with your email address, and you land on "My notes" with "Signed in as" and your username at the top. Add a note, press Log out, and you are back on the login page.

If your app needs nearly every page protected, Django 5.1 and later also offer LoginRequiredMiddleware, which inverts the default: every view requires login unless you mark it with @login_not_required. The decorator and mixin used here are easier to follow while you learn.

Step 5 · Add password reset with the console email backend

The reset flow is four views that django.contrib.auth.urls already routed: a form that asks for an email address, a "check your inbox" page, the page the emailed link opens to set a new password, and a "done" page. The link carries a token that is signed with your SECRET_KEY, works once, and expires after PASSWORD_RESET_TIMEOUT, three days by default.

During development you want those emails printed in the server terminal, not sent. Django 6.1 configures email through a MAILERS setting, and the settings.py that startproject generated already points the default mailer at the console backend. Look at it:

Bash
grep -A 4 '^MAILERS' config/settings.py

The older EMAIL_BACKEND and EMAIL_HOST style settings are deprecated in 6.1, and Django refuses to start if you set them alongside MAILERS, so do not copy them from older guides. Append only the sender address to config/settings.py:

Bash
cat >> config/settings.py <<'PY'
DEFAULT_FROM_EMAIL = "notes@example.com"
PY

Add the four templates. The email text itself comes from the template that ships with Django's admin app, so you do not need to write one yet:

Bash
cat > accounts/templates/registration/password_reset_form.html <<'HTML'
{% extends "base.html" %}
{% block title %}Reset your password{% endblock %}
{% block content %}
  <h1>Reset your password</h1>
  <p>Enter the email address on your account and we will send you a link.</p>
  <form method="post">
    {% csrf_token %}
    {{ form.as_div }}
    <button type="submit">Send the link</button>
  </form>
{% endblock %}
HTML

cat > accounts/templates/registration/password_reset_done.html <<'HTML'
{% extends "base.html" %}
{% block title %}Check your email{% endblock %}
{% block content %}
  <h1>Check your email</h1>
  <p>If an account uses that address, a reset link is on its way.</p>
{% endblock %}
HTML

cat > accounts/templates/registration/password_reset_confirm.html <<'HTML'
{% extends "base.html" %}
{% block title %}Choose a new password{% endblock %}
{% block content %}
  {% if validlink %}
    <h1>Choose a new password</h1>
    <form method="post">
      {% csrf_token %}
      {{ form.as_div }}
      <button type="submit">Save password</button>
    </form>
  {% else %}
    <h1>This link has expired</h1>
    <p>It may have been used already. <a href="{% url 'password_reset' %}">Ask for a new one</a>.</p>
  {% endif %}
{% endblock %}
HTML

cat > accounts/templates/registration/password_reset_complete.html <<'HTML'
{% extends "base.html" %}
{% block title %}Password changed{% endblock %}
{% block content %}
  <h1>Password changed</h1>
  <p><a href="{% url 'login' %}">Log in with your new password</a>.</p>
{% endblock %}
HTML

The "check your email" page says the same thing whether or not the address has an account. That is deliberate: a different message would let anyone test which email addresses are registered.

Settings are read once at start-up, so stop the server with Ctrl+C and start it again:

Bash
uv run python manage.py runserver

Check it worked

In the browser, log out, follow "Forgotten your password?" and enter the email you signed up with. You land on "Check your email". The server terminal prints the message: headers such as Subject: Password reset on 127.0.0.1:8000 and To: with your address, then a link that starts http://127.0.0.1:8000/accounts/reset/. Open the link, choose a new password, and log in with it. Open the same link again and you see "This link has expired", because the token stops working once the password changes.

Step 6 · Prove it with the Django test client

Clicking through works once. Tests keep it working. The test client sends requests to your views without a network, and during a test run Django swaps the email backend for an in-memory one, so sent messages collect in django.core.mail.outbox instead of printing. Replace notes/tests.py. The passwords in it exist only in the temporary test database:

Bash
cat > notes/tests.py <<'PY'
import re

from django.core import mail
from django.test import TestCase
from django.urls import reverse

from accounts.models import User

from .models import Note


class SignUpAndLoginTests(TestCase):
    def test_sign_up_creates_user_and_logs_them_in(self):
        response = self.client.post(
            reverse("sign_up"),
            {
                "username": "amina",
                "email": "amina@example.com",
                "password1": "a-long-Passphrase-71",
                "password2": "a-long-Passphrase-71",
            },
        )
        self.assertRedirects(response, reverse("notes:list"))
        user = User.objects.get(username="amina")
        self.assertEqual(int(self.client.session["_auth_user_id"]), user.pk)

    def test_anonymous_visitor_is_sent_to_login(self):
        response = self.client.get(reverse("notes:list"))
        self.assertRedirects(response, reverse("login") + "?next=/")

    def test_logout_only_accepts_post(self):
        User.objects.create_user("kofi", "kofi@example.com", "a-long-Passphrase-72")
        self.client.login(username="kofi", password="a-long-Passphrase-72")
        self.assertEqual(self.client.get(reverse("logout")).status_code, 405)
        response = self.client.post(reverse("logout"))
        self.assertRedirects(response, reverse("login"))
        self.assertNotIn("_auth_user_id", self.client.session)


class NotePrivacyTests(TestCase):
    def setUp(self):
        self.amina = User.objects.create_user("amina", "amina@example.com", "a-long-Passphrase-71")
        self.kofi = User.objects.create_user("kofi", "kofi@example.com", "a-long-Passphrase-72")
        self.kofi_note = Note.objects.create(owner=self.kofi, text="Kofi: buy bread")
        self.client.force_login(self.amina)

    def test_list_shows_only_own_notes(self):
        Note.objects.create(owner=self.amina, text="Amina: call the plumber")
        response = self.client.get(reverse("notes:list"))
        self.assertContains(response, "Amina: call the plumber")
        self.assertNotContains(response, "Kofi: buy bread")

    def test_new_note_belongs_to_the_author(self):
        self.client.post(reverse("notes:create"), {"text": "Amina: pay school fees"})
        note = Note.objects.get(text="Amina: pay school fees")
        self.assertEqual(note.owner, self.amina)

    def test_cannot_delete_someone_elses_note(self):
        response = self.client.post(reverse("notes:delete", args=[self.kofi_note.pk]))
        self.assertEqual(response.status_code, 404)
        self.assertTrue(Note.objects.filter(pk=self.kofi_note.pk).exists())


class PasswordResetTests(TestCase):
    def test_emailed_link_sets_a_new_password(self):
        user = User.objects.create_user("amina", "amina@example.com", "a-long-Passphrase-71")
        response = self.client.post(reverse("password_reset"), {"email": "amina@example.com"})
        self.assertRedirects(response, reverse("password_reset_done"))
        self.assertEqual(len(mail.outbox), 1)

        link = re.search(r"http://testserver(/accounts/reset/\S+/)", mail.outbox[0].body).group(1)
        response = self.client.get(link, follow=True)
        set_password_url = response.redirect_chain[-1][0]
        response = self.client.post(
            set_password_url,
            {"new_password1": "another-Long-phrase-93", "new_password2": "another-Long-phrase-93"},
        )
        self.assertRedirects(response, reverse("password_reset_complete"))
        user.refresh_from_db()
        self.assertTrue(user.check_password("another-Long-phrase-93"))

    def test_unknown_email_gets_the_same_page_and_no_email(self):
        response = self.client.post(reverse("password_reset"), {"email": "nobody@example.com"})
        self.assertRedirects(response, reverse("password_reset_done"))
        self.assertEqual(len(mail.outbox), 0)
PY
uv run python manage.py test

When you open the emailed link, Django moves the token out of the URL into your session and redirects to a set-password address, so the token does not leak through the Referer header. That is why the test follows the redirect before posting the new password.

Check it worked

The runner prints Found 8 test(s)., a line of eight dots, Ran 8 tests and OK. To see a test catch a real mistake, change get_queryset in NoteDelete to return Note.objects.all() and run the tests again: test_cannot_delete_someone_elses_note fails because Kofi's note is deleted. Put the filter back afterwards.

Step 7 · Get it ready for real users

The flow works, but three settings must change before anyone else uses it:

  • Email: point the default entry in MAILERS at the SMTP backend or your provider's backend, and read the host, user and password from environment variables, never from literals in settings.py. A reset email that never arrives locks people out for good.
  • HTTPS: passwords and session cookies must only travel encrypted. Set SESSION_COOKIE_SECURE = True and CSRF_COOKIE_SECURE = True once the site is served over HTTPS, along with the DEBUG, SECRET_KEY and ALLOWED_HOSTS changes from the first Django tutorial.
  • Shared devices: where a family shares one phone or people sign in at a cyber café, put the Log out button somewhere obvious, as the base template does, and consider SESSION_EXPIRE_AT_BROWSER_CLOSE = True so a session does not outlive the browser.

Stop the development server with Ctrl+C in its terminal.

When you have finished experimenting, remove the demo project:

Bash
cd ~
rm -rf ~/notes-auth-demo

Check it worked

ls ~/notes-auth-demo reports No such file or directory, and nothing answers on http://127.0.0.1:8000/.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.