Form (Django)

A Django Form is a class that defines, renders, and validates an HTML form in Python. You declare fields with validation rules, render the form in a template, and call is_valid() to check submitted data before using it.

Django

Forms handle the tedious, error-prone parts of input: generating HTML widgets, validating data, and reporting errors. You subclass forms.Form and declare fields like CharField, EmailField, IntegerField, each with validators and a widget.

In a view you instantiate the form (empty for GET, with request.POST for a submission), call form.is_valid() to run validation, and then read the cleaned, type-converted data from form.cleaned_data. If invalid, re-rendering the same form shows error messages automatically.

When a form maps directly to a model, ModelForm saves you from re-declaring the fields by generating them from the model. Plain Form is for inputs not tied to a model, like a contact or search form.

Syntax

class ContactForm(forms.Form):
    email = forms.EmailField()

Examples

Python

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()

def contact(request):
    form = ContactForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        send(form.cleaned_data)
    return render(request, "contact.html", {"form": form})

Learn it in a lesson

See also

Back to the Dictionary