[null, {"document_url": "http://docs.pythontab.com/django/django1.5/topics/forms/index.html", "unformatted_src": "/statics/img/qrcode.jpg", "src": "https://docs.pythontab.com/statics/img/qrcode.jpg", "formatted_filename": "qrcode", "rendered_width": 100, "rendered_height": 100}]
Working with forms¶

About this document

This document provides an introduction to Django’s form handling features. For a more detailed look at specific areas of the forms API, see The Forms API, Form fields, and Form and field validation.

django.forms is Django’s form-handling library.

While it is possible to process form submissions just using Django’s HttpRequest class, using the form library takes care of a number of common form-related tasks. Using it, you can:


The library deals with these concepts:

A class that corresponds to an HTML form widget, e.g. <input type="text"> or <textarea>. This handles rendering of the widget as HTML.
A class that is responsible for doing validation, e.g. an EmailField that makes sure its data is a valid email address.
A collection of fields that knows how to validate itself and display itself as HTML.
Form Media
The CSS and JavaScript resources that are required to render a form.

The library is decoupled from the other Django components, such as the database layer, views and templates. It relies only on Django settings, a couple of django.utils helper functions and Django’s internationalization hooks (but you’re not required to be using internationalization features to use this library).

Form objects¶

A Form object encapsulates a sequence of form fields and a collection of validation rules that must be fulfilled in order for the form to be accepted. Form classes are created as subclasses of django.forms.Form and make use of a declarative style that you’ll be familiar with if you’ve used Django’s database models.

For example, consider a form used to implement “contact me” functionality on a personal Web site:

If your form is going to be used to directly add or edit a Django model, you can use a ModelForm to avoid duplicating your model description.

Using a form in a view¶

The standard pattern for processing a form in a view looks like this:

There are three possible code paths here:

The distinction between Bound and unbound forms is important:

Handling file uploads with a form¶

To see how to handle file uploads with your form, see Binding uploaded files to a form.

Processing the data from a form¶

Once is_valid() returns True, the successfully validated form data will be in the form.cleaned_data dictionary. This data will have been converted nicely into Python types for you.

In the above example, cc_myself will be a boolean value. Likewise, fields such as IntegerField and FloatField convert values to a Python int and float respectively.

Read-only fields are not available in form.cleaned_data (and setting a value in a custom clean() method won’t have any effect). These fields are displayed as text rather than as input elements, and thus are not posted back to the server.

Extending the earlier example, here’s how the form data could be processed:


For more on sending email from Django, see Sending email.

Displaying a form using a template¶

Forms are designed to work with the Django template language. In the above example, we passed our ContactForm instance to the template using the context variable form. Here’s a simple example template:

The form only outputs its own fields; it is up to you to provide the surrounding <form> tags and the submit button.

If your form includes uploaded files, be sure to include enctype="multipart/form-data" in the form element. If you wish to write a generic template that will work whether or not the form has files, you can use the is_multipart() attribute on the form:

Forms and Cross Site Request Forgery protection

form.as_p will output the form with each form field and accompanying label wrapped in a paragraph. Here’s the output for our example template:

Note that each form field has an ID attribute set to id_<field-name>, which is referenced by the accompanying label tag. This is important for ensuring forms are accessible to assistive technology such as screen reader software. You can also customize the way in which labels and ids are generated.

You can also use form.as_table to output table rows (you’ll need to provide your own <table> tags) and form.as_ul to output list items.

Customizing the form template¶

If the default generated HTML is not to your taste, you can completely customize the way a form is presented using the Django template language. Extending the above example:

Each named form-field can be output to the template using {{ form.name_of_field }}, which will produce the HTML needed to display the form widget. Using {{ form.name_of_field.errors }} displays a list of form errors, rendered as an unordered list. This might look like:

Looping over the form’s fields¶

Within this loop, {{ field }} is an instance of BoundField. BoundField also has the following attributes, which can be useful in your templates:

{{ field.label }}
The label of the field, e.g. Email address.
{{ field.label_tag }}
The field’s label wrapped in the appropriate HTML <label> tag, e.g. <label for="id_email">Email address</label>
{{ field.value }}
The value of the field. e.g email@example.com
{{ field.html_name }}
The name of the field that will be used in the input element’s name field. This takes the form prefix into account, if it has been set.
{{ field.help_text }}
Any help text that has been associated with the field.
{{ field.errors }}
Outputs a <ul class="errorlist"> containing any validation errors corresponding to this field. You can customize the presentation of the errors with a {% for error in field.errors %} loop. In this case, each object in the loop is a simple string containing the error message.
{{ field.is_hidden }}

Looping over hidden and visible fields¶

Reusable form templates¶

Further topics¶
