Django Forms
Forms are how users send information to your site: searching, signing up, leaving feedback. Django's forms framework generates the HTML, checks every value the user submits and gives you clean Python data, which saves you writing a lot of fiddly and error-prone code.
Why use Django forms?
Handling a form by hand means reading raw strings from request.POST, converting types, checking for missing or invalid values, showing error messages and refilling the fields the user already typed. Django forms do all of this, plus they work with Django's CSRF protection to block forged submissions.
Defining a form
Forms usually live in a forms.py file in your app. Let's collect feedback after campus events:
events/forms.py
from django import forms
class FeedbackForm(forms.Form):
name = forms.CharField(max_length=80)
email = forms.EmailField()
rating = forms.IntegerField(min_value=1, max_value=5, help_text="1 = poor, 5 = excellent")
message = forms.CharField(widget=forms.Textarea, required=False)
def clean_name(self):
name = self.cleaned_data["name"]
if any(char.isdigit() for char in name):
raise forms.ValidationError("Names can't contain numbers.")
return name
def clean(self):
cleaned_data = super().clean()
rating = cleaned_data.get("rating")
message = cleaned_data.get("message")
if rating is not None and rating <= 2 and not message:
self.add_error("message", "Please tell us what went wrong so we can improve.")
return cleaned_data
Each form field has a type that decides how input is validated and converted, and a widget that decides the HTML used to display it. All fields are required unless you pass required=False.
| Field | Converts to | Default widget |
|---|---|---|
CharField | str | Text input |
EmailField | str (checked as an email) | Email input |
IntegerField / DecimalField | int / Decimal | Number input |
BooleanField | bool | Checkbox (add required=False if it may be left unticked) |
ChoiceField(choices=...) | str | Drop-down select |
DateField / DateTimeField | date / datetime | Text input (use a widget with type="date" for a picker) |
How validation works
You can try a form in the shell. Pass the submitted data, then call is_valid():
>>> from events.forms import FeedbackForm
>>> form = FeedbackForm({"name": "Achieng", "email": "achieng@", "rating": "7"})
>>> form.is_valid()
False
>>> form.errors["email"]
['Enter a valid email address.']
>>> form.errors["rating"]
['Ensure this value is less than or equal to 5.']
>>> form = FeedbackForm({"name": "Achieng", "email": "achieng@example.com", "rating": "2"})
>>> form.is_valid()
False
>>> form.errors["message"]
['Please tell us what went wrong so we can improve.']
>>> form = FeedbackForm({"name": "Achieng", "email": "achieng@example.com", "rating": "5"})
>>> form.is_valid()
True
>>> form.cleaned_data
{'name': 'Achieng', 'email': 'achieng@example.com', 'rating': 5, 'message': ''}
Notice that rating arrived as the string "5" but cleaned_data holds the integer 5. Validation runs in this order:
- Each field's built-in checks (required, type,
max_length,min_value...). - Each
clean_<fieldname>()method, for rules about one field. It must return the value. - The form's
clean()method, for rules involving several fields.
Reading form.cleaned_data before calling is_valid() (it doesn't exist yet), or using cleaned_data["rating"] inside clean(). If the rating failed its own validation, it won't be in cleaned_data and you'll get a KeyError. Use cleaned_data.get("rating") as shown above.
Using the form in a view
This is the standard pattern for any form view. Learn it well; you'll write it many times.
events/views.py
from django.contrib import messages
from django.shortcuts import redirect, render
from .forms import FeedbackForm
def feedback(request):
if request.method == "POST":
form = FeedbackForm(request.POST) # bound form: filled with submitted data
if form.is_valid():
data = form.cleaned_data
# In a real app: save it, or email it with django.core.mail.send_mail
messages.success(request, f"Asante, {data['name']}! Your feedback was received.")
return redirect("events:event_list")
else:
form = FeedbackForm() # unbound form: empty
return render(request, "events/feedback.html", {"form": form})
events/urls.py (add to urlpatterns)
path("feedback/", views.feedback, name="feedback"),
Three things happen here:
- On GET, an empty form is shown.
- On an invalid POST, the view falls through to
render()with the bound form, which redisplays the user's input with error messages next to the fields. - On a valid POST, the view does its work and redirects. This "Post/Redirect/Get" pattern stops the browser from resubmitting the form if the user refreshes the page.
The messages.success() message appears on the next page if your base template displays messages (see Template Inheritance).
Rendering the form in a template
events/templates/events/feedback.html
{% extends "base.html" %}
{% block content %}
<h1>Event feedback</h1>
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Send feedback</button>
</form>
{% endblock %}
{{ form }} outputs every field with its label, input, help text and errors, each wrapped in a <div>. Note that Django creates the inputs but not the <form> tag or the button, so you write those yourself. For full control over the layout, render fields one at a time:
{{ 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 %}
You can also render one field's label, input, help text and errors together with {{ form.email.as_field_group }}.
CSRF protection
{% csrf_token %} adds a hidden secret value to the form. Django's CSRF middleware checks it on every POST, which stops other websites from tricking a logged-in user's browser into submitting your forms.
Leaving out {% csrf_token %}. Every POST from that form then fails with 403 Forbidden: CSRF verification failed. Request aborted. Add the tag inside every <form method="post">. Don't add it to GET forms such as a search box, because the token would appear in the URL.
Key points
- Define forms as classes in
forms.py; each field validates and converts one value. - Call
is_valid(), then read clean, typed values fromcleaned_data. - Add custom rules in
clean_<field>()orclean(), raisingValidationErroror callingadd_error(). - In views: GET shows an empty form, invalid POST redisplays errors, valid POST does the work and redirects.
- Always include
{% csrf_token %}in POST forms.
Tip: use the ← and → keys to move between pages.
