Explain it simply
Django forms in plain language
All form data that arrives from a browser is strings, and a user can type anything. A Django Form is a class that declares 'these fields are needed, they must be this type, and they must follow these rules'. Give it the data and the form checks it, returns the valid values as proper Python types, and prepares readable error messages for the fields that are wrong.
Picture a bank teller. They take your withdrawal slip and check for empty boxes, whether the amount is a number, and whether the signature matches the name. If something is wrong they hand the slip back and point at the box to fix; only a correct slip goes into the system.
Problem → Why → Solution
The problem: reading request.POST by hand
Say a signup view reads request.POST directly. If the age field is missing you get a KeyError and a 500; if it is present it is the string "21", so comparing age < 13 raises a TypeError. You feel safe because the HTML has a required attribute, but a request sent with curl never passes through a browser. And when the user makes a mistake, there is nowhere to show which field was wrong.
def signup(request):
username = request.POST["username"] # KeyError if missing -> 500
age = request.POST["age"] # always a str, e.g. "21"
if age < 13: # TypeError: str < int
return HttpResponse("Too young")
User.objects.create(username=username) # no email/length checks at allWhat a Form class fixes
A form converts each field to its declared type (IntegerField gives an int, DateField gives a date) and collects missing, malformed and out-of-range values into errors instead of raising. It validates on the server, so it also checks requests that bypass the browser. And the errors are attached to each field, ready to be shown back in the template.
Core concept: bound forms, is_valid() and cleaned_data
A form class declares its fields as class attributes: CharField, EmailField, IntegerField, DateField and so on. Creating SignupForm() with no data gives an unbound form, the empty form you show the user first. Creating SignupForm(request.POST) with data gives a bound form whose data can be validated. form.is_bound tells you which one you have.
Calling is_valid() runs validation in three stages. First, each field converts its string to a Python value and checks its built-in rules (required, max_length, min_value, email format). Second, if a clean_<field>() method such as clean_username() exists, it is called for that field and whatever it returns goes into cleaned_data, so it can also normalise the value, for example to lowercase. Third, clean() runs after all fields and checks rules that involve several fields, such as two matching passwords or a check-out date after the check-in date.
| Attribute / method | What it gives you |
|---|---|
| form.is_valid() | True when there are no errors; runs validation once |
| form.cleaned_data | validated values, already converted to Python types |
| form.errors | field name → list of messages; form-wide ones under __all__ |
| form.add_error(field, msg) | attaches an error to one field from inside clean() |
Remember one rule: read cleaned_data only after is_valid() returns True, and never go back to request.POST. A field that failed its own validation is missing from cleaned_data, so inside clean() read values with .get(), as in cleaned.get("password"); square brackets can raise a KeyError.
Every field is required=True by default, and CharField strips leading and trailing spaces for you. A widget only decides which HTML input is drawn: PasswordInput hides the typed characters but does not change validation at all. The field decides how data is checked; the widget decides how it is displayed, and those are two separate jobs.
- Bind the raw string data
- Each field converts and checks
- clean_<field>() refines a field
- clean() checks across fields
- Result: cleaned_data or errors
Validation does not stop at the first error; it collects all of them so the user sees every problem at once.
General pattern
class NameForm(forms.Form):
field_a = forms.CharField(max_length=50)
field_b = forms.IntegerField(min_value=0, required=False)
def clean_field_a(self): # one field: return the cleaned value
return self.cleaned_data["field_a"]
def clean(self): # several fields: use .get()
cleaned = super().clean()
return cleanedDeclare fields as class attributes, add clean_<field>() for a field that needs an extra rule, and override clean() for rules that involve more than one field, always calling super().clean().
Worked example: valid and invalid signup data
Forms need settings, so to run as a single file the script calls settings.configure() and django.setup() first; a real project does not need those two lines. The same form is tried three ways: with no data, with good data, and with data where every field is wrong.
import django
from django.conf import settings
# Single-file demo only: a real project already has settings.py.
settings.configure()
django.setup()
from django import forms
class SignupForm(forms.Form):
username = forms.CharField(max_length=20)
email = forms.EmailField()
age = forms.IntegerField(min_value=13)
password = forms.CharField(widget=forms.PasswordInput, min_length=8)
confirm = forms.CharField(widget=forms.PasswordInput)
def clean_username(self):
name = self.cleaned_data["username"].lower()
if name in {"admin", "root"}:
raise forms.ValidationError("This username is reserved.")
return name
def clean(self):
cleaned = super().clean()
if cleaned.get("password") != cleaned.get("confirm"):
self.add_error("confirm", "Passwords do not match.")
return cleaned
empty = SignupForm()
print("unbound:", empty.is_bound)
good = SignupForm({"username": "Mya", "email": "mya@example.com", "age": "21",
"password": "s3cret-pass", "confirm": "s3cret-pass"})
print("valid:", good.is_valid())
print(good.cleaned_data["username"], type(good.cleaned_data["age"]).__name__)
bad = SignupForm({"username": "Admin", "email": "not-an-email", "age": "9",
"password": "short", "confirm": "different"})
print("valid:", bad.is_valid())
for field, messages in bad.errors.items():
print(f"{field}: {list(messages)}")Code breakdown
- Fields with built-in rules
age = forms.IntegerField(min_value=13)IntegerField turns "21" into the int 21, and min_value rejects anything below 13. Django writes the error message for you.
- Per-field rule
def clean_username(self):Runs after the CharField checks pass. It lowercases the username and raises ValidationError for reserved names; the returned value ('mya') is what lands in cleaned_data.
- Cross-field rule
if cleaned.get("password") != cleaned.get("confirm"):Compares the two passwords. 'short' failed min_length=8, so it is not in cleaned_data; .get() returns None instead of raising KeyError. add_error() attaches the message to the confirm field.
- Bound vs unbound
print("unbound:", empty.is_bound)SignupForm() has no data, so is_bound is False; it cannot be validated and is only used to show an empty form on a GET request.
- Typed cleaned_data
print(good.cleaned_data["username"], type(good.cleaned_data["age"]).__name__)Shows the username already lowercased and age as an int, no longer a str.
- Reading the errors
for field, messages in bad.errors.items():errors is a dict-like object keyed by field name. list(messages) gives the plain message strings; in a template you would show them with {{ form.age.errors }}.
unbound: False
valid: True
mya int
valid: False
username: ['This username is reserved.']
email: ['Enter a valid email address.']
age: ['Ensure this value is greater than or equal to 13.']
password: ['Ensure this value has at least 8 characters (it has 5).']
confirm: ['Passwords do not match.']Using a form in a view, and ModelForm
Using a form in a view always follows the same shape: on GET show an unbound form; on POST build a bound form and validate it; if valid, do the work and redirect; if not, render the same template with the form and its errors. Redirecting after success (Post/Redirect/Get) stops a refresh from submitting the form twice.
from django import forms
from django.shortcuts import redirect, render
from .models import Task
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ["title", "due_date"] # explicit allowlist, never "__all__"
def add_task(request):
if request.method == "POST":
form = TaskForm(request.POST)
if form.is_valid():
task = form.save(commit=False)
task.owner = request.user # set server-side, not from the form
task.save()
return redirect("task-list")
else:
form = TaskForm()
return render(request, "tasks/add_task.html", {"form": form})<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>A ModelForm builds its form fields from the model's fields and saves to the database with form.save(). {% csrf_token %} adds the hidden token that CsrfViewMiddleware checks; without it the POST is rejected with a 403. {{ form.as_p }} renders every field with its label, input and error messages.
In real projects
Forms in real projects
Every place that accepts data from a user is a form: contact forms, registration, a checkout address, a blog post editor, search filters. Even in APIs built with Django REST Framework, serializers follow the same bound data → validate → cleaned data shape as forms.
- Uniqueness: a rule like 'an account with this email already exists' is checked with a query in clean_email(), backed by a unique constraint in the database, because two requests can arrive at the same moment.
- Date ranges: bookings and report filters keep the 'end date after start date' rule in clean().
- Uploads: FileField and ImageField need size and extension validation, plus limits through settings such as FILE_UPLOAD_MAX_MEMORY_SIZE.
- Tests: post invalid data and assert status 200 plus the expected message inside form.errors.
Common mistakes
Common mistakes with forms
Using fields = "__all__" on a ModelForm
Today the model has only title and body, but the moment someone adds an is_featured or price field next month, the form starts accepting it too. A user can then change it just by adding is_featured=on to the POST data. List the allowed fields explicitly with fields = [...].
Indexing cleaned_data with [...] inside clean()
clean() runs even when field errors exist. If the password field failed min_length it is not in cleaned_data, so cleaned["password"] raises KeyError and the user sees a 500 page instead of an error message. Use .get() and compare only when both values are present.
Showing a fresh form when validation fails
When is_valid() is False, building a new SignupForm() before rendering wipes everything the user typed and hides the error messages. Pass the bound form back to the template so both the values and the errors survive.
Mini challenge
Mini challenge: a hotel booking form
Write a BookingForm with a check-in date, a check-out date, a number of guests and an optional promo code. Put the 'check-out after check-in' rule in clean(), try three sets of data, and print either the number of nights or the first error for each field.
- check_in and check_out are DateFields; guests allows only 1 to 6
- promo_code is required=False and clean_promo_code() uppercases it
- clean() raises a form-wide ValidationError when check-out <= check-in
- Print the number of nights when valid, or each field's error when not
import django
from django.conf import settings
settings.configure()
django.setup()
from django import forms
class BookingForm(forms.Form):
# TODO: check_in, check_out (dates), guests (1-6), promo_code (optional)
def clean_promo_code(self):
# TODO: return the code in uppercase
...
def clean(self):
cleaned = super().clean()
# TODO: raise ValidationError if check_out is not after check_in
return cleaned
def try_booking(data):
# TODO: validate; print nights + guests + code, or the errors
...
# TODO: one valid booking, one with reversed dates, one with bad valuesExpected: The first booking prints 'OK: 3 night(s), 2 guest(s), code SPRING', the second prints an __all__ error, and the third prints two errors: check_out (not a date) and guests (more than 6).
Show hint
A ValidationError raised in clean() lands in errors["__all__"], not on a field. Subtracting two dates gives a timedelta whose .days is the number of nights. CharField already strips surrounding spaces by default.
Show solution
import django
from django.conf import settings
settings.configure()
django.setup()
from django import forms
class BookingForm(forms.Form):
check_in = forms.DateField()
check_out = forms.DateField()
guests = forms.IntegerField(min_value=1, max_value=6)
promo_code = forms.CharField(required=False, max_length=10)
def clean_promo_code(self):
return self.cleaned_data["promo_code"].upper()
def clean(self):
cleaned = super().clean()
start, end = cleaned.get("check_in"), cleaned.get("check_out")
if start and end and end <= start:
raise forms.ValidationError("Check-out must be after check-in.")
return cleaned
def try_booking(data):
form = BookingForm(data)
if form.is_valid():
nights = (form.cleaned_data["check_out"] - form.cleaned_data["check_in"]).days
guests = form.cleaned_data["guests"]
code = form.cleaned_data["promo_code"] or "-"
print(f"OK: {nights} night(s), {guests} guest(s), code {code}")
else:
for field, messages in form.errors.items():
print(f"ERROR {field}: {messages[0]}")
try_booking({"check_in": "2026-03-01", "check_out": "2026-03-04",
"guests": "2", "promo_code": " spring "})
try_booking({"check_in": "2026-03-04", "check_out": "2026-03-01", "guests": "2"})
try_booking({"check_in": "2026-03-01", "check_out": "tomorrow", "guests": "9"})Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A form without data is unbound (for display); a form with data is bound (for validation).
- is_valid() runs field validation, clean_<field>() and clean() in order and collects every error in errors.
- After validation use the typed cleaned_data; inside clean(), read it with .get().
- In a view use POST → is_valid() → redirect, and re-render the bound form when it is invalid.
- Give a ModelForm an explicit fields list and put {% csrf_token %} in the template.
Django — Getting Started — Django Software Foundation