Recommended preparation: set up a Django project and read the Django tutorial overview before trying the code.
Use forms.Form to declare fields, validate user input and render controls. A form class keeps validation in one place instead of reading unverified request.POST values throughout each view.
my_app/forms.py — simple form class
from django import forms
class MyForm(forms.Form):
student_id = forms.IntegerField(required=False, min_value=1)
name = forms.CharField(max_length=80)
This form validates that the name is present and at most 80 characters. If an ID is provided, it must be an integer of at least 1. We will add a dropdown, checkbox and radio group below.
my_app/views.py
from django.shortcuts import render
from .forms import MyForm
def form_demo(request):
form = MyForm(request.POST if request.method == "POST" else None)
result = None
if request.method == "POST" and form.is_valid():
result = form.cleaned_data
return render(request, "form_demo.html", {"form": form, "result": result})
my_app/templates/form_demo.html
<h1>Student form</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Check input</button>
</form>
{% if result %}
<p>Name: {{ result.name }}</p>
<p>ID: {{ result.student_id|default:"Not provided" }}</p>
{% endif %}
forms.py — validated select options
from django import forms
CLASS_CHOICES = [
("three", "Three"),
("four", "Four"),
("five", "Five"),
]
class ClassForm(forms.Form):
name = forms.CharField(max_length=80)
cl = forms.ChoiceField(choices=CLASS_CHOICES, initial="four")
Submitted option values are strings such as four; an integer-like option value is also received as a string. Only listed choices pass form validation. For basic HTML controls see the dropdown list tutorial.
forms.py — optional checkbox
class AgreeForm(forms.Form):
name = forms.CharField(max_length=80)
subscribe = forms.BooleanField(required=False, initial=True)
For a checkbox, required=False allows the unchecked state. Read form.cleaned_data["subscribe"] as a Python Boolean, rather than comparing the raw POST value against a string. See HTML checkboxes.
forms.py — radio group
LEVEL_CHOICES = [("b", "Beginner"), ("i", "Intermediate")]
class LevelForm(forms.Form):
level = forms.ChoiceField(
choices=LEVEL_CHOICES,
widget=forms.RadioSelect,
initial="b",
)
Use one radio group when the user must select exactly one value. The widget determines how the HTML is displayed; validation still comes from ChoiceField. See HTML radio buttons.
Complete Django form with text, dropdown, checkbox and radio fields
from django import forms
class RegistrationForm(forms.Form):
name = forms.CharField(max_length=80)
student_id = forms.IntegerField(required=False, min_value=1)
class_choice = forms.ChoiceField(
choices=[("three", "Three"), ("four", "Four")]
)
subscribe = forms.BooleanField(required=False)
level = forms.ChoiceField(
choices=[("b", "Beginner"), ("i", "Intermediate")],
widget=forms.RadioSelect,
)
Template: render field errors explicitly
<form method="post">
{% csrf_token %}
{% for field in form %}
<p>{{ field.label_tag }} {{ field }}</p>
{% for error in field.errors %}
<p class="text-danger">{{ error }}</p>
{% endfor %}
{% endfor %}
<button type="submit">Submit</button>
</form>
forms.Form is ideal when you need validation without automatically saving to the database. Use forms.ModelForm when fields correspond to a model and you plan to store validated records. The MySQL insert lesson demonstrates a ModelForm.
form.is_valid() first; use field names, not labels.BooleanField normalizes this.required=False only if the field is genuinely optional.EmailField, validated integer and a multiline text area
from django import forms
class ContactForm(forms.Form):
email = forms.EmailField()
age = forms.IntegerField(min_value=1, max_value=120)
comment = forms.CharField(widget=forms.Textarea, max_length=500)
A custom clean_name() validator
from django import forms
class PersonForm(forms.Form):
name = forms.CharField(max_length=80)
def clean_name(self):
name = self.cleaned_data["name"].strip()
if len(name) < 2:
raise forms.ValidationError("Use at least two characters.")
return name
Testing a form class in the Django shell
form = RegistrationForm({"name": "Alex", "student_id": "20", "class_choice": "three", "level": "b"})
if form.is_valid():
print(form.cleaned_data["student_id"]) # integer 20
Inspect field-level validation errors
form = RegistrationForm({"name": "Alex", "student_id": "wrong", "class_choice": "three", "level": "b"})
if not form.is_valid():
print(form.errors.as_json())
Pre-fill an unbound form on the initial GET request
form = MyForm(initial={"name": "Guest"})
Use initial to suggest starting values. Initial values are not a substitute for validation, and they do not override invalid submitted data.
A checked checkbox is required before this form passes validation
class ConsentForm(forms.Form):
consent = forms.BooleanField(required=True)
Yes. A single forms.Form can contain several field and widget types.
Prefer form.cleaned_data after is_valid(). That gives validated and converted Python values.
Protection requires the CSRF middleware and a {% csrf_token %} field in ordinary POST templates. Keep both enabled.
Previous: GET and POST forms
Next: Query string parameters
Browse the complete Django tutorial series.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.