Skip to content
devtoolbox.cc

Django · Chapter 7 of 8

Django forms: fields, validation, clean methods and CSRF

13 min study · Examples checked with Django 6.1 on Python 3.14 ·

Chapter 2 read query parameters by hand: get the string, convert it, check it, build an error. Django forms do all of that systematically. A form class declares its fields; given submitted data, it converts each value to a Python type, runs the validation rules, collects errors per field and renders itself as HTML, with the entered values kept. This chapter adds a “suggest a lesson” page with a form, and covers validation hooks, the view pattern every Django form uses, CSRF protection and one-time messages.

Declare a form

Create catalog/forms.py:

from django import forms

from .models import Lesson


class SuggestionForm(forms.Form):
    name = forms.CharField(max_length=80)
    email = forms.EmailField(required=False, help_text="Only if you want a reply.")
    topic = forms.CharField(max_length=120, label="Lesson topic")
    level = forms.ChoiceField(choices=Lesson.Level.choices, initial=Lesson.Level.BEGINNER)
    minutes = forms.IntegerField(min_value=5, max_value=180, required=False)
    notify = forms.BooleanField(required=False, label="Tell me when it is published")

    def clean_topic(self):
        topic = " ".join(self.cleaned_data["topic"].split())
        if Lesson.objects.filter(title__iexact=topic).exists():
            raise forms.ValidationError("There is already a lesson with this title.")
        return topic

    def clean(self):
        cleaned = super().clean()
        if cleaned.get("notify") and not cleaned.get("email"):
            self.add_error("email", "Enter an email address to be notified.")
        return cleaned

Each field has a type that decides conversion and validation: CharField gives a string, EmailField checks the address format, IntegerField gives an int within min_value and max_value, ChoiceField accepts only the listed values (here the same Level choices as the model, so the two can’t drift apart), and BooleanField gives True for a ticked checkbox. Fields are required unless required=False; an unticked checkbox sends nothing at all, which is why optional booleans need it. label, initial and help_text control how the field appears.

Validation hooks

Validation runs in a fixed order when you call is_valid(). First each field converts and checks its own value. Then a method named clean_<field> runs for that field, if you defined one: clean_topic normalizes whitespace and rejects topics that already exist as lessons, returning the cleaned value. Last, clean() runs once with all values and handles rules involving several fields; add_error attaches the message to a specific field. Valid values end up in form.cleaned_data, already converted:

SuggestionForm({"name": "Ada", "topic": "  loops ", "level": "expert", "minutes": "3", "notify": "on"})
is_valid() -> False
topic:   There is already a lesson with this title.
level:   Select a valid choice. expert is not one of the available choices.
minutes: Ensure this value is greater than or equal to 5.
email:   Enter an email address to be notified.

SuggestionForm({"name": "Ada", "topic": "  Context   managers ", "level": "advanced", "minutes": "45"})
is_valid() -> True
cleaned_data: {'name': 'Ada', 'email': '', 'topic': 'Context managers', 'level': 'advanced',
               'minutes': 45, 'notify': False}

All errors are reported at once, "45" became the integer 45, and the unsent checkbox became False. Never read request.POST directly once you have a form: use cleaned_data, which only contains values that passed every check.

The view: one URL, two methods

A form created without data, SuggestionForm(), is unbound: it renders empty fields with their initial values and has no errors. Created with data, SuggestionForm(request.POST), it is bound and can be validated. The standard view uses both. Add suggest to catalog/views.py, importing messages from django.contrib and SuggestionForm from .forms, and register it as path("suggest/", views.suggest, name="suggest"):

def suggest(request):
    if request.method == "POST":
        form = SuggestionForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            messages.success(request, f"Thanks, {data['name']}! We noted “{data['topic']}”.")
            return redirect("catalog:suggest")
    else:
        form = SuggestionForm()
    return render(request, "catalog/suggest.html", {"form": form})

On GET the view shows an empty form. On POST it validates; if valid, it acts on cleaned_data and redirects (post/redirect/get, so a refresh doesn’t submit twice), and if not, it falls through to render with the bound form, which now shows the user’s values and the error messages. A real site would save the suggestion or email it; chapter 8 saves objects directly with model forms.

Render the form with CSRF protection

Create catalog/templates/catalog/suggest.html:

{% extends "catalog/base.html" %}

{% block content %}
  <h1>Suggest a lesson</h1>
  {% for message in messages %}<p class="notice">{{ message }}</p>{% endfor %}
  <form method="post" novalidate>
    {% csrf_token %}
    {{ form.non_field_errors }}
    {% for field in form %}
      <div class="field">
        {{ field.label_tag }} {{ field }}
        {% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}
        {{ field.errors }}
      </div>
    {% endfor %}
    <button type="submit">Send suggestion</button>
  </form>
{% endblock %}

Looping over the form gives each field’s label, widget, help text and errors, so you control the markup around them; {{ form }} alone renders everything with default HTML. Widgets carry the field’s rules as HTML attributes, for example <input type="text" name="name" maxlength="80" required id="id_name">, so browsers check before submitting. novalidate turns those browser checks off on this page so you can see the server’s messages while testing. With a blank name and an existing topic, the page shows “This field is required.” and “There is already a lesson with this title.” under the right fields.

{% csrf_token %} adds a hidden field with a secret token. Django’s CSRF middleware rejects any POST without a matching token with status 403. Without it, another website could make a logged-in visitor’s browser submit forms to your site, a cross-site request forgery. Every POST form in a Django template needs the tag; the protection is on by default, and keeping it on is the point.

Messages after a redirect

After the redirect, the page has to say the suggestion arrived, but the form data is gone. The messages framework stores a short note in the session and shows it on the next page, once: messages.success(request, ...) in the view, and the {% for message in messages %} loop in the template, which displays “Thanks, Ada! We noted “Generators”.” and then forgets it. messages.error, warning and info work the same way, and the base template is a good place for the loop so every page shows messages.

Practice

Add a reason field (a CharField with widget=forms.Textarea, at most 500 characters, optional) and a rule in clean() that advanced suggestions must give a reason of at least 20 characters. Write a test with Django’s TestCase and test client that posts an advanced suggestion without a reason and checks the error appears.

Answer check: in clean(), test cleaned.get("level") == "advanced" and len(cleaned.get("reason", "")) < 20 and call self.add_error("reason", ...). In the test, self.client.post(reverse("catalog:suggest"), {...}) returns status 200 (the form is shown again), and self.assertFormError(response.context["form"], "reason", "...") checks the message. The test client skips CSRF checks by default, so the test needs no token.

Summary

A form class declares typed fields; is_valid() converts values, runs field checks, then clean_<field> methods, then clean() for cross-field rules, and fills cleaned_data. Views show an unbound form on GET, validate a bound form on POST, redirect on success and re-render with errors on failure. Include {% csrf_token %} in every POST form and use messages to confirm actions after redirecting.

All Django chapters