Django Form Classes: Validate Fields and Render Widgets

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.

On this page — Show page sectionsHide page sections

Handle form submission in the view

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.

Checkbox with BooleanField

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.

Radio buttons with RadioSelect

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.

Combine the fields in one form

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,
    )

Show validation errors

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>

Form versus ModelForm

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.

Troubleshooting

  • Values missing from cleaned_data: call form.is_valid() first; use field names, not labels.
  • Choice rejected: submit the declared choice key, not the displayed label.
  • Checkbox unexpectedly false: unchecked checkboxes are commonly absent from raw POST data; BooleanField normalizes this.
  • Form field is required: set required=False only if the field is genuinely optional.

Additional field validation patterns

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.

Require consent instead of allowing an unchecked checkbox

A checked checkbox is required before this form passes validation

class ConsentForm(forms.Form):
    consent = forms.BooleanField(required=True)

Frequently asked questions

Can I mix text boxes, select menus and radio inputs?

Yes. A single forms.Form can contain several field and widget types.

Should I use request.POST.get() when I have a form class?

Prefer form.cleaned_data after is_valid(). That gives validated and converted Python values.

Does Django automatically protect form submissions from CSRF?

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.

Additional references

Back to top ↑




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer