Forms Introduction

Django forms handle rendering, validation and cleaning of user input.

Syntaxclass MyForm(forms.Form): ...

Django's forms framework does the tedious work of displaying input fields, validating submitted data and returning clean Python values. You define a form as a class of fields.

A bound form (created with data) can tell you if it is_valid() and expose the cleaned values in cleaned_data.

Example

Example · python
# blog/forms.py
from django import forms

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

# In a view:
# form = ContactForm(request.POST)
# if form.is_valid():
#     data = form.cleaned_data

When to use it

  • A developer uses a Django Form class to validate user-submitted contact form data before sending an email.
  • A team relies on Django forms for automatic HTML widget generation, avoiding hand-crafting input elements.
  • A developer uses Form.cleaned_data to safely access validated field values after is_valid() returns True.

More examples

Define a simple form class

Defines a contact form with name, email, and message fields using Django's forms module.

Example · python
from django import forms

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

Render form in a template

Renders all form fields as paragraphs with as_p() and includes the required CSRF token.

Example · html
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Send</button>
</form>

Validate and access cleaned data

Shows the standard view pattern: bind POST data, validate, access cleaned_data, redirect on success.

Example · python
def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data["name"]
            email = form.cleaned_data["email"]
            # send email...
            return redirect("thanks")
    else:
        form = ContactForm()
    return render(request, "contact.html", {"form": form})

Discussion

  • Be the first to comment on this lesson.