Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 77 ยท Forms

Django Forms

Learn how Django forms define fields, validate user input, expose cleaned_data and errors, pick widgets, set initial values and render safely in templates.

Almost every web application accepts input: a signup page, a search box, a comment, a checkout. Raw HTML forms send everything as text, and you cannot trust any of it. Someone may leave a required field empty, type "abc" where you expect a number, or paste HTML into a text box. You need to check the data, convert it to Python types, remember what the user typed and show helpful errors.

Django's form system does this work for you. You describe a form once as a Python class. Django then renders it as HTML, validates the submitted data, converts values to the right Python types, and collects error messages. In this lesson you build forms from fields, see what is_valid(), cleaned_data and errors do, choose widgets, set initial values and render a form safely in a template. The next lessons cover custom validation, model forms and using forms in views.

flowchart LR
    D["Submitted data<br/>(strings)"] --> F["Form(data)"]
    F --> V{"is_valid()"}
    V -->|"yes"| C["cleaned_data<br/>(Python types)"]
    V -->|"no"| E["errors<br/>(messages per field)"]

A form takes raw strings, runs every field's validation and produces either clean Python values or error messages.

Your first form

A form is a class that inherits from django.forms.Form. Each class attribute is a field, and the field type decides how the value is validated and converted. A CharField keeps text, an IntegerField produces an int, a BooleanField produces True or False, and so on.

Python Valid and invalid data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the three cases:

  • Unbound form: SignupForm() has no data. is_bound is False, and is_valid() is always False. You use unbound forms to show a blank page for the first time.
  • Bound form: SignupForm(data) attaches data. Calling is_valid() runs validation on every field. For the good data, cleaned_data holds Python values: the age is the integer 36, the checkbox string "on" became True.
  • Invalid form: errors maps each field name to its messages. Notice the newsletter checkbox: an unchecked checkbox sends nothing, and BooleanField(required=False) turns the missing value into False. Also notice that cleaned_data on an invalid form contains only the fields that passed. Never read cleaned_data before is_valid() returned True.

The data you pass is a dictionary of strings. In a real view it is request.POST (see request data), which behaves like a dictionary of strings too.

Fields are required by default. That is the opposite of what many people expect, but it is the safe default. Add required=False for optional fields.

Common field types

Django ships fields for almost every kind of input. The most useful ones:

Field Cleaned value Notes
CharField str max_length, min_length, strip=True by default
IntegerField, FloatField, DecimalField int, float, Decimal min_value, max_value
BooleanField bool use required=False for optional checkboxes
EmailField, URLField, SlugField str built-in format validation
DateField, TimeField, DateTimeField date, time, datetime accept several input formats
ChoiceField, MultipleChoiceField str, list choices=[(value, label), ...]
FileField, ImageField uploaded file covered in forms in views

Every field accepts a few common arguments: label (the text shown to the user), required, initial, help_text, widget and validators. All of them are optional.

Widgets: how a field is drawn

A field validates and converts data. A widget decides which HTML element represents the field. The two are separate on purpose: a CharField shows a one-line <input type="text"> by default, but with widget=forms.Textarea the same field renders a multi-line box.

Widgets also take an attrs dictionary for any extra HTML attributes, such as class, placeholder or rows. The following example renders a form with a template, field by field, which is how you will usually take control of the layout.

Python Widgets and field-by-field rendering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at what the output shows:

  • Each {{ field }} renders the widget as HTML, including maxlength, required and the attributes you passed in attrs. For the bound form with errors, Django also adds accessibility attributes (aria-invalid, aria-describedby).
  • {{ field.label }}, {{ field.help_text }} and {{ field.errors }} let you place each piece exactly where your design needs it.
  • The message Great <b>tutorial</b> was escaped inside the textarea (&lt;b&gt;). Django templates escape every variable by default, which protects you against HTML injection. You do not need to do anything for this to work.

Quick rendering shortcuts

When you do not need custom layout, render the whole form with one expression:

HTML
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}   {# or {{ form }} , {{ form.as_div }} , {{ form.as_table }} #}
  <button type="submit">Save</button>
</form>

{{ form }} uses the form's default style (a <div> per field in current Django versions). The {% csrf_token %} tag is required for POST forms in templates rendered with a request; we explain why in Handling Forms in Views.

Initial data and changes

initial gives a field a starting value for an unbound form. It never fills in a bound form: when the user submits a form, what they typed always wins. You can set it on the field, or per form instance, which is more flexible because the value can depend on the current user or request.

Python Initial values, prefix and has_changed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few things to note from this example:

  • form["display_name"].value() returns the value that will be displayed: the user's data for a bound form, the initial value otherwise.
  • changed_data lists the fields whose submitted value differs from the initial value. It helps you update only what changed.
  • A disabled field ignores whatever the browser submits and always uses its initial value. That makes it a safe way to show a value the user must not edit. (A hidden input without disabled can be tampered with by anyone, so never trust it for security.)
  • prefix="billing" renames every field to billing-display_name, which lets two forms of the same class live on one page without their data colliding.
  • base_fields shows the fields in declaration order, which is also the order they are rendered in.

Why not just read request.POST?

You could read request.POST["age"] yourself, call int() on it and check for errors in a pile of if statements. Forms do that work consistently:

  • One place for validation rules, reused wherever the form appears.
  • Type conversion from strings to Python objects.
  • Safe re-display: on failure the form shows what the user typed together with the error messages.
  • Escaping and HTML attributes handled for you.
  • A security baseline: choice fields reject values that are not in choices, and file and number fields reject malformed input.

Forms are not tied to models. You can build a form for a search box or a contact message that never touches the database. When a form does map to a model, a ModelForm generates the fields for you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You create SignupForm() with no arguments and call is_valid(). What is the result?

    A form without data is unbound, and an unbound form is never valid. You use it to show a blank form for the first time.
  2. 2. When is it safe to read form.cleaned_data?

    cleaned_data is filled while validation runs. On an invalid form it contains only the fields that passed, so rely on it only after is_valid() returned True.
  3. 3. What is the difference between a field and a widget?

    Fields handle validation and conversion to Python types. Widgets render the HTML input and can be swapped without changing the validation rules.
  4. 4. A user submits a bound form. Which value is shown in the input when it is rendered again?

    Initial values only apply to unbound forms. A bound form shows the submitted data, so users do not lose what they typed when there is an error.

Summary

  • A form class declares fields; each field validates input and converts it to a Python type.
  • An unbound form has no data and is never valid; a bound form is created with submitted data.
  • is_valid() runs validation; afterwards use cleaned_data for good values and errors for messages.
  • Fields are required by default; use required=False for optional ones.
  • Widgets choose the HTML element, and attrs adds attributes such as class and placeholder.
  • initial pre-fills unbound forms, changed_data lists edits, disabled=True ignores browser input and prefix namespaces field names.
  • Templates escape output automatically; render with {{ form }} or field by field.

Next, learn how to write your own rules in Form Validation.