Django Formsยง

Validate user input and return Python objects

Defining Forms

Forms are composed of fields, which have a widget.

from django.utils.translation import gettext_lazy as _
from django import forms

class ContactForm(forms.Form):

    name = forms.CharField(label=_("Your Name"),

    email = forms.EmailField(label=_("Email address"))

Instantiating a Form

Unbound forms don't have data associated with them, but they can be rendered:

form = ContactForm()

Bound forms have specific data associated, which can be validated:

form = ContactForm(data=request.POST, files=request.FILES)

Accessing Fields

Two ways to access fields on a Form instance

Validating the Form

Field Validation

Field Cleaning

Rendering Forms

Three primary "whole-form" output modes:

<tr><th><label for="id_name">Name:</label></th>
  <td><input id="id_name" type="text" name="name" maxlength="255" /></td></tr>
<tr><th><label for="id_email">Email:</label></th>
  <td><input id="id_email" type="text" name="email" maxlength="Email address" /></td></tr>
<tr><th><label for="id_confirm_email">Confirm email:</label></th>
  <td><input id="id_confirm_email" type="text" name="confirm_email" maxlength="Confirm" /></td></tr>

Controlling Form Output

{% for field in form %}
{{ field.label_tag }}: {{ field }}
{{ field.errors }}
{% endfor %}
{{ form.non_field_errors }}

Additional rendering properties: