Django Forms
Handling an HTML form by hand is tedious: render the inputs, read request.POST, convert strings to numbers and dates, check required fields, show error messages, and re-fill the inputs when something's wrong. Django's forms library does all of that. You describe the fields once, and the form object can render itself, validate submitted data, and give you clean Python values.
Declaring a form
A form is a class with field attributes, similar to a model:
# books/forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=50)
email = forms.EmailField()
age = forms.IntegerField(min_value=13, required=False)
message = forms.CharField(widget=forms.Textarea)| Field | Python value after cleaning | Default widget |
|---|---|---|
CharField |
str |
<input type="text"> |
EmailField, URLField |
str (validated) |
type="email" / type="url" |
IntegerField, DecimalField, FloatField |
int / Decimal / float |
type="number" |
BooleanField |
bool |
checkbox |
DateField |
datetime.date |
type="text" |
ChoiceField(choices=…) |
str |
<select> |
MultipleChoiceField |
list |
<select multiple> |
Every field is required unless you pass required=False.
Bound vs. unbound forms
A form created without data is unbound — it's for displaying an empty form. A form created with data (usually request.POST) is bound and can be validated with is_valid(). After validation, cleaned_data contains converted Python values; errors contains messages per field.
import django
from django.conf import settings
settings.configure()
django.setup()
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=50)
email = forms.EmailField()
age = forms.IntegerField(min_value=13, required=False)
empty = ContactForm()
print("unbound:", empty.is_bound)
good = ContactForm({"name": "Trang", "email": "trang@example.com", "age": "27"})
print("valid:", good.is_valid())
print(good.cleaned_data)
bad = ContactForm({"name": "", "email": "nope", "age": "9"})
print("valid:", bad.is_valid())
for field, errors in bad.errors.items():
print(f" {field}: {errors[0]}")unbound: False
valid: True
{'name': 'Trang', 'email': 'trang@example.com', 'age': 27}
valid: False
name: This field is required.
email: Enter a valid email address.
age: Ensure this value is greater than or equal to 13.
Notice age arrived as the string "27" and came out as the integer 27.
Rendering a form
A form renders its fields as HTML. In a template you can output the whole form with {{ form }}, or lay out each field yourself with {{ form.name.label_tag }}, {{ form.name }} and {{ form.name.errors }}:
import django
from django.conf import settings
settings.configure(TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django import forms
from django.template import Template, Context
class SearchForm(forms.Form):
q = forms.CharField(label="Search", max_length=40)
sort = forms.ChoiceField(choices=[("new", "Newest"), ("top", "Top rated")])
form = SearchForm(initial={"sort": "top"})
print(form["q"])
print(form["q"].label_tag())
print(form["sort"])
t = Template("{% for field in form %}{{ field.label }}: {{ field.value|default:'-' }}\n{% endfor %}")
print(t.render(Context({"form": form})))<input type="text" name="q" maxlength="40" required id="id_q">
<label for="id_q">Search:</label>
<select name="sort" id="id_sort">
<option value="new">Newest</option>
<option value="top" selected>Top rated</option>
</select>
Search: -
Sort: top
initial pre-fills values in an unbound form without making it bound.
The standard view pattern
Almost every form view follows the same shape:
def contact(request):
if request.method == "POST":
form = ContactForm(request.POST) # bound
if form.is_valid():
send_message(**form.cleaned_data)
return redirect("thanks") # Post/Redirect/Get
else:
form = ContactForm() # unbound
return render(request, "contact.html", {"form": form})<!-- contact.html -->
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Send</button>
</form>If validation fails, the same template is rendered again with the bound form, which now shows the user's input and the error messages. Here's the full cycle running in the playground:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", {
"signup.html": "{% for f in form %}{{ f.name }}=[{{ f.value|default:'' }}] {{ f.errors.0 }}\n{% endfor %}",
})]}}],
)
django.setup()
from django import forms
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import path
from django.test import Client
SIGNUPS = []
class SignupForm(forms.Form):
username = forms.CharField(min_length=3)
email = forms.EmailField()
def signup(request):
if request.method == "POST":
form = SignupForm(request.POST)
if form.is_valid():
SIGNUPS.append(form.cleaned_data["username"])
return redirect("/thanks/")
else:
form = SignupForm()
return render(request, "signup.html", {"form": form})
def thanks(request):
return HttpResponse(f"Welcome! Members: {SIGNUPS}")
urls.urlpatterns = [path("signup/", signup), path("thanks/", thanks)]
c = Client()
print(c.get("/signup/").content.decode())
r = c.post("/signup/", {"username": "ab", "email": "ab@example"})
print(r.status_code)
print(r.content.decode())
r = c.post("/signup/", {"username": "abby", "email": "abby@example.com"}, follow=True)
print(r.content.decode())username=[]
email=[]
200
username=[ab] Ensure this value has at least 3 characters (it has 2).
email=[ab@example] Enter a valid email address.
Welcome! Members: ['abby']
Widgets and attributes
A field's widget controls the HTML. Pass attrs to add CSS classes or placeholders:
import django
from django.conf import settings
settings.configure()
django.setup()
from django import forms
class CommentForm(forms.Form):
text = forms.CharField(widget=forms.Textarea(attrs={"rows": 3, "class": "input"}))
rating = forms.IntegerField(widget=forms.NumberInput(attrs={"min": 1, "max": 5}))
email = forms.EmailField(widget=forms.EmailInput(attrs={"placeholder": "you@example.com"}))
secret = forms.CharField(widget=forms.PasswordInput)
form = CommentForm()
for name in ["text", "rating", "email", "secret"]:
print(form[name])<textarea name="text" cols="40" rows="3" class="input" required id="id_text">
</textarea>
<input type="number" name="rating" min="1" max="5" required id="id_rating">
<input type="email" name="email" placeholder="you@example.com" maxlength="320" required id="id_email">
<input type="password" name="secret" required id="id_secret">
Tip: Third-party packages such as django-crispy-forms or django-widget-tweaks help style forms with Bootstrap or Tailwind without writing widget attributes by hand.
Test yourself
When is form.cleaned_data available?
- Immediately after creating the form
- After
form.is_valid()has been called - Only in templates
- After saving to the database
What is a "bound" form?
- A form linked to a model
- A form created with submitted data
- A form inside a template
- A form with no fields
After a successful POST, what should a form view usually return?
- The same page with the form
- A redirect
- A 404
- Nothing