Menu
CoddyTech

Signing Up

Part of the Users and Accounts section of Coddy's Django journey. Lesson 4 of 16.

Only ada can log in: a visitor has no way to make an account. Django has no signup page, but it has the form for one, UserCreationForm in django.contrib.auth.forms.

It is a ModelForm for User with three fields: username, password1 and password2. It refuses a name that is taken, two passwords that differ, and a password that breaks the rules in AUTH_PASSWORD_VALIDATORS (too short, too common, only digits). Its save() stores the password hashed, never as plain text. Try it in the Shell tab:

>>> from django.contrib.auth.forms import UserCreationForm
>>> form = UserCreationForm({"username": "kim", "password1": "tea-kettle-42", "password2": "tea-kettle-42"})
>>> form.is_valid()
True
>>> user = form.save()
>>> user.password == "tea-kettle-42"
False

In a view it works like NoteForm: one branch for the POST, one for the empty form.

challenge icon

Challenge

Easy

Let visitors make an account.

  1. In notes/views.py, write a view signup that shows a UserCreationForm in notes/signup.html (ready for you). When the form is valid, save it and redirect to login.
  2. In notes/urls.py, add signup/ named signup.
  3. In base.html, next to Log in, link Sign up to {% url 'notes:signup' %}.

Make an account at /signup/, then log in with it.

Try it yourself

from django.shortcuts import get_object_or_404, redirect, render

from .forms import NoteForm
from .models import Note


def note_list(request):
    notes = Note.objects.all()
    return render(request, "notes/note_list.html", {"notes": notes})


def note_detail(request, pk):
    note = get_object_or_404(Note, pk=pk)
    return render(request, "notes/note_detail.html", {"note": note})


def note_create(request):
    if request.method == "POST":
        form = NoteForm(request.POST)
        if form.is_valid():
            note = form.save()
            return redirect("notes:detail", pk=note.pk)
    else:
        form = NoteForm()
    return render(request, "notes/note_form.html", {"form": form})


def note_edit(request, pk):
    note = get_object_or_404(Note, pk=pk)
    if request.method == "POST":
        form = NoteForm(request.POST, instance=note)
        if form.is_valid():
            form.save()
            return redirect("notes:detail", pk=note.pk)
    else:
        form = NoteForm(instance=note)
    return render(request, "notes/note_form.html", {"form": form, "note": note})


def note_delete(request, pk):
    note = get_object_or_404(Note, pk=pk)
    if request.method == "POST":
        note.delete()
        return redirect("notes:list")
    return render(request, "notes/note_confirm_delete.html", {"note": note})

All lessons in Users and Accounts

Practice on your own: Django playground