The Forms API

About this document

This document covers the gritty details of Django’s forms API. You shouldread the introduction to working with formsfirst.

Bound and unbound forms

A Form instance is either bound to a set of data, or unbound.

  • If it’s bound to a set of data, it’s capable of validating that dataand rendering the form as HTML with the data displayed in the HTML.
  • If it’s unbound, it cannot do validation (because there’s no data tovalidate!), but it can still render the blank form as HTML.
  • class Form
  • To create an unbound Form instance, instantiate the class:
  1. >>> f = ContactForm()

To bind data to a form, pass the data as a dictionary as the first parameter toyour Form class constructor:

  1. >>> data = {'subject': 'hello',
  2. ... 'message': 'Hi there',
  3. ... 'sender': 'foo@example.com',
  4. ... 'cc_myself': True}
  5. >>> f = ContactForm(data)

In this dictionary, the keys are the field names, which correspond to theattributes in your Form class. The values are the data you’re trying tovalidate. These will usually be strings, but there’s no requirement that they bestrings; the type of data you pass depends on the Field, as we’ll seein a moment.

  • Form.is_bound
  • If you need to distinguish between bound and unbound form instances at runtime,check the value of the form’s is_bound attribute:
  1. >>> f = ContactForm()
  2. >>> f.is_bound
  3. False
  4. >>> f = ContactForm({'subject': 'hello'})
  5. >>> f.is_bound
  6. True

Note that passing an empty dictionary creates a bound form with empty data:

  1. >>> f = ContactForm({})
  2. >>> f.is_bound
  3. True

If you have a bound Form instance and want to change the data somehow,or if you want to bind an unbound Form instance to some data, createanother Form instance. There is no way to change data in aForm instance. Once a Form instance has been created, youshould consider its data immutable, whether it has data or not.

Using forms to validate data

  • Form.clean()
  • Implement a clean() method on your Form when you must add customvalidation for fields that are interdependent. SeeCleaning and validating fields that depend on each other for example usage.

  • Form.is_valid()

  • The primary task of a Form object is to validate data. With a boundForm instance, call the is_valid() method to run validationand return a boolean designating whether the data was valid:
  1. >>> data = {'subject': 'hello',
  2. ... 'message': 'Hi there',
  3. ... 'sender': 'foo@example.com',
  4. ... 'cc_myself': True}
  5. >>> f = ContactForm(data)
  6. >>> f.is_valid()
  7. True

Let’s try with some invalid data. In this case, subject is blank (an error,because all fields are required by default) and sender is not a validemail address:

  1. >>> data = {'subject': '',
  2. ... 'message': 'Hi there',
  3. ... 'sender': 'invalid email address',
  4. ... 'cc_myself': True}
  5. >>> f = ContactForm(data)
  6. >>> f.is_valid()
  7. False
  • Form.errors
  • Access the errors attribute to get a dictionary of errormessages:
  1. >>> f.errors
  2. {'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}

In this dictionary, the keys are the field names, and the values are lists ofstrings representing the error messages. The error messages are storedin lists because a field can have multiple error messages.

You can access errors without having to callis_valid() first. The form’s data will be validated the first timeeither you call is_valid() or access errors.

The validation routines will only get called once, regardless of how many timesyou access errors or call is_valid(). This means thatif validation has side effects, those side effects will only be triggered once.

  • Form.errors.as_data()
  • Returns a dict that maps fields to their original ValidationErrorinstances.
  1. >>> f.errors.as_data()
  2. {'sender': [ValidationError(['Enter a valid email address.'])],
  3. 'subject': [ValidationError(['This field is required.'])]}

Use this method anytime you need to identify an error by its code. Thisenables things like rewriting the error’s message or writing custom logic in aview when a given error is present. It can also be used to serialize the errorsin a custom format (e.g. XML); for instance, as_json()relies on as_data().

The need for the asdata() method is due to backwards compatibility.Previously ValidationError instances were lost as soon as theirrendered error messages were added to the Form.errors dictionary.Ideally Form.errors would have stored ValidationError instancesand methods with an as prefix could render them, but it had to be donethe other way around in order not to break code that expects rendered errormessages in Form.errors.

  • Form.errors.asjson(_escape_html=False)
  • Returns the errors serialized as JSON.
  1. >>> f.errors.as_json()
  2. {"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
  3. "subject": [{"message": "This field is required.", "code": "required"}]}

By default, as_json() does not escape its output. If you are using it forsomething like AJAX requests to a form view where the client interprets theresponse and inserts errors into the page, you’ll want to be sure to escape theresults on the client-side to avoid the possibility of a cross-site scriptingattack. You can do this in JavaScript with element.textContent = errorTextor with jQuery’s $(el).text(errorText) (rather than its .html()function).

If for some reason you don’t want to use client-side escaping, you can alsoset escape_html=True and error messages will be escaped so you can use themdirectly in HTML.

  • Form.errors.getjson_data(_escape_html=False)
  • Returns the errors as a dictionary suitable for serializing to JSON.Form.errors.as_json() returns serialized JSON, while this returns theerror data before it’s serialized.

The escape_html parameter behaves as described inForm.errors.as_json().

  • Form.adderror(_field, error)
  • This method allows adding errors to specific fields from within theForm.clean() method, or from outside the form altogether; for instancefrom a view.

The field argument is the name of the field to which the errorsshould be added. If its value is None the error will be treated asa non-field error as returned by Form.non_field_errors().

The error argument can be a string, or preferably an instance ofValidationError. See Raising ValidationError for best practiceswhen defining form errors.

Note that Form.add_error() automatically removes the relevant field fromcleaned_data.

  • Form.haserror(_field, code=None)
  • This method returns a boolean designating whether a field has an error witha specific error code. If code is None, it will return Trueif the field contains any errors at all.

To check for non-field errors useNON_FIELD_ERRORS as the field parameter.

Behavior of unbound forms

It’s meaningless to validate a form with no data, but, for the record, here’swhat happens with unbound forms:

  1. >>> f = ContactForm()
  2. >>> f.is_valid()
  3. False
  4. >>> f.errors
  5. {}

Dynamic initial values

  • Form.initial
  • Use initial to declare the initial value of form fields atruntime. For example, you might want to fill in a username field with theusername of the current session.

To accomplish this, use the initial argument to a Form.This argument, if given, should be a dictionary mapping field names to initialvalues. Only include the fields for which you’re specifying an initial value;it’s not necessary to include every field in your form. For example:

  1. >>> f = ContactForm(initial={'subject': 'Hi there!'})

These values are only displayed for unbound forms, and they’re not used asfallback values if a particular value isn’t provided.

If a Field defines initialand youinclude initial when instantiating the Form, then the latterinitial will have precedence. In this example, initial is provided bothat the field level and at the form instance level, and the latter getsprecedence:

  1. >>> from django import forms
  2. >>> class CommentForm(forms.Form):
  3. ... name = forms.CharField(initial='class')
  4. ... url = forms.URLField()
  5. ... comment = forms.CharField()
  6. >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
  7. >>> print(f)
  8. <tr><th>Name:</th><td><input type="text" name="name" value="instance" required></td></tr>
  9. <tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
  10. <tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>

Checking which form data has changed

  • Form.has_changed()
  • Use the has_changed() method on your Form when you need to check if theform data has been changed from the initial data.
  1. >>> data = {'subject': 'hello',
  2. ... 'message': 'Hi there',
  3. ... 'sender': 'foo@example.com',
  4. ... 'cc_myself': True}
  5. >>> f = ContactForm(data, initial=data)
  6. >>> f.has_changed()
  7. False

When the form is submitted, we reconstruct it and provide the original dataso that the comparison can be done:

  1. >>> f = ContactForm(request.POST, initial=data)
  2. >>> f.has_changed()

has_changed() will be True if the data from request.POST differsfrom what was provided in initial or False otherwise. Theresult is computed by calling Field.has_changed() for each field in theform.

  • Form.changed_data
  • The changed_data attribute returns a list of the names of the fields whosevalues in the form’s bound data (usually request.POST) differ from what wasprovided in initial. It returns an empty list if no data differs.
  1. >>> f = ContactForm(request.POST, initial=data)
  2. >>> if f.has_changed():
  3. ... print("The following fields changed: %s" % ", ".join(f.changed_data))
  4. >>> f.changed_data
  5. ['subject', 'message']

Accessing the fields from the form

  • Form.fields
  • You can access the fields of Form instance from its fieldsattribute:
  1. >>> for row in f.fields.values(): print(row)
  2. ...
  3. <django.forms.fields.CharField object at 0x7ffaac632510>
  4. <django.forms.fields.URLField object at 0x7ffaac632f90>
  5. <django.forms.fields.CharField object at 0x7ffaac3aa050>
  6. >>> f.fields['name']
  7. <django.forms.fields.CharField object at 0x7ffaac6324d0>

You can alter the field of Form instance to change the way it ispresented in the form:

  1. >>> f.as_table().split('\n')[0]
  2. '<tr><th>Name:</th><td><input name="name" type="text" value="instance" required></td></tr>'
  3. >>> f.fields['name'].label = "Username"
  4. >>> f.as_table().split('\n')[0]
  5. '<tr><th>Username:</th><td><input name="name" type="text" value="instance" required></td></tr>'

Beware not to alter the base_fields attribute because this modificationwill influence all subsequent ContactForm instances within the same Pythonprocess:

  1. >>> f.base_fields['name'].label = "Username"
  2. >>> another_f = CommentForm(auto_id=False)
  3. >>> another_f.as_table().split('\n')[0]
  4. '<tr><th>Username:</th><td><input name="name" type="text" value="class" required></td></tr>'

Accessing “clean” data

  • Form.cleaned_data
  • Each field in a Form class is responsible not only for validatingdata, but also for “cleaning” it – normalizing it to a consistent format. Thisis a nice feature, because it allows data for a particular field to be input ina variety of ways, always resulting in consistent output.

For example, DateField normalizes input into aPython datetime.date object. Regardless of whether you pass it a string inthe format '1994-07-15', a datetime.date object, or a number of otherformats, DateField will always normalize it to a datetime.date objectas long as it’s valid.

Once you’ve created a Form instance with a set of data and validatedit, you can access the clean data via its cleaned_data attribute:

  1. >>> data = {'subject': 'hello',
  2. ... 'message': 'Hi there',
  3. ... 'sender': 'foo@example.com',
  4. ... 'cc_myself': True}
  5. >>> f = ContactForm(data)
  6. >>> f.is_valid()
  7. True
  8. >>> f.cleaned_data
  9. {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}

Note that any text-based field – such as CharField or EmailField –always cleans the input into a string. We’ll cover the encoding implicationslater in this document.

If your data does not validate, the cleaned_data dictionary containsonly the valid fields:

  1. >>> data = {'subject': '',
  2. ... 'message': 'Hi there',
  3. ... 'sender': 'invalid email address',
  4. ... 'cc_myself': True}
  5. >>> f = ContactForm(data)
  6. >>> f.is_valid()
  7. False
  8. >>> f.cleaned_data
  9. {'cc_myself': True, 'message': 'Hi there'}

cleaneddata will always _only contain a key for fields defined in theForm, even if you pass extra data when you define the Form. In thisexample, we pass a bunch of extra fields to the ContactForm constructor,but cleaned_data contains only the form’s fields:

  1. >>> data = {'subject': 'hello',
  2. ... 'message': 'Hi there',
  3. ... 'sender': 'foo@example.com',
  4. ... 'cc_myself': True,
  5. ... 'extra_field_1': 'foo',
  6. ... 'extra_field_2': 'bar',
  7. ... 'extra_field_3': 'baz'}
  8. >>> f = ContactForm(data)
  9. >>> f.is_valid()
  10. True
  11. >>> f.cleaned_data # Doesn't contain extra_field_1, etc.
  12. {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}

When the Form is valid, cleaneddata will include a key and value for_all its fields, even if the data didn’t include a value for some optionalfields. In this example, the data dictionary doesn’t include a value for thenick_name field, but cleaned_data includes it, with an empty value:

  1. >>> from django import forms
  2. >>> class OptionalPersonForm(forms.Form):
  3. ... first_name = forms.CharField()
  4. ... last_name = forms.CharField()
  5. ... nick_name = forms.CharField(required=False)
  6. >>> data = {'first_name': 'John', 'last_name': 'Lennon'}
  7. >>> f = OptionalPersonForm(data)
  8. >>> f.is_valid()
  9. True
  10. >>> f.cleaned_data
  11. {'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}

In this above example, the cleaned_data value for nick_name is set to anempty string, because nick_name is CharField, and CharFields treatempty values as an empty string. Each field type knows what its “blank” valueis – e.g., for DateField, it’s None instead of the empty string. Forfull details on each field’s behavior in this case, see the “Empty value” notefor each field in the “Built-in Field classes” section below.

You can write code to perform validation for particular form fields (based ontheir name) or for the form as a whole (considering combinations of variousfields). More information about this is in Form and field validation.

Outputting forms as HTML

The second task of a Form object is to render itself as HTML. To do so,print it:

  1. >>> f = ContactForm()
  2. >>> print(f)
  3. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>
  4. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>
  5. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>
  6. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>

If the form is bound to data, the HTML output will include that dataappropriately. For example, if a field is represented by an<input type="text">, the data will be in the value attribute. If afield is represented by an <input type="checkbox">, then that HTML willinclude checked if appropriate:

  1. >>> data = {'subject': 'hello',
  2. ... 'message': 'Hi there',
  3. ... 'sender': 'foo@example.com',
  4. ... 'cc_myself': True}
  5. >>> f = ContactForm(data)
  6. >>> print(f)
  7. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" required></td></tr>
  8. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" required></td></tr>
  9. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" value="foo@example.com" required></td></tr>
  10. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" checked></td></tr>

This default output is a two-column HTML table, with a <tr> for each field.Notice the following:

  • For flexibility, the output does not include the <table> and</table> tags, nor does it include the <form> and </form>tags or an <input type="submit"> tag. It’s your job to do that.
  • Each field type has a default HTML representation. CharField isrepresented by an <input type="text"> and EmailField by an<input type="email">.BooleanField is represented by an <input type="checkbox">. Notethese are merely sensible defaults; you can specify which HTML to use fora given field by using widgets, which we’ll explain shortly.
  • The HTML name for each tag is taken directly from its attribute namein the ContactForm class.
  • The text label for each field – e.g. 'Subject:', 'Message:' and'Cc myself:' is generated from the field name by converting allunderscores to spaces and upper-casing the first letter. Again, notethese are merely sensible defaults; you can also specify labels manually.
  • Each text label is surrounded in an HTML <label> tag, which pointsto the appropriate form field via its id. Its id, in turn, isgenerated by prepending 'id_' to the field name. The idattributes and <label> tags are included in the output by default, tofollow best practices, but you can change that behavior.
  • The output uses HTML5 syntax, targeting <!DOCTYPE html>. For example,it uses boolean attributes such as checked rather than the XHTML styleof checked='checked'.Although <table> output is the default output style when you print aform, other output styles are available. Each style is available as a method ona form object, and each rendering method returns a string.

as_p()

  • Form.as_p()
  • as_p() renders the form as a series of <p> tags, with each <p>containing one field:
  1. >>> f = ContactForm()
  2. >>> f.as_p()
  3. '<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" required></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>'
  4. >>> print(f.as_p())
  5. <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>
  6. <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>
  7. <p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></p>
  8. <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>

as_ul()

  • Form.as_ul()
  • asul() renders the form as a series of <li> tags, with each<li> containing one field. It does _not include the <ul> or</ul>, so that you can specify any HTML attributes on the <ul> forflexibility:
  1. >>> f = ContactForm()
  2. >>> f.as_ul()
  3. '<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>'
  4. >>> print(f.as_ul())
  5. <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>
  6. <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>
  7. <li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>
  8. <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>

as_table()

  • Form.as_table()
  • Finally, as_table() outputs the form as an HTML <table>. This isexactly the same as print. In fact, when you print a form object,it calls its as_table() method behind the scenes:
  1. >>> f = ContactForm()
  2. >>> f.as_table()
  3. '<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>'
  4. >>> print(f)
  5. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>
  6. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>
  7. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>
  8. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>

Styling required or erroneous form rows

  • Form.error_css_class
  • Form.required_css_class
  • It’s pretty common to style form rows and fields that are required or haveerrors. For example, you might want to present required form rows in bold andhighlight errors in red.

The Form class has a couple of hooks you can use to add classattributes to required rows or to rows with errors: set theForm.error_css_class and/or Form.required_css_classattributes:

  1. from django import forms
  2.  
  3. class ContactForm(forms.Form):
  4. error_css_class = 'error'
  5. required_css_class = 'required'
  6.  
  7. # ... and the rest of your fields here

Once you’ve done that, rows will be given "error" and/or "required"classes, as needed. The HTML will look something like:

  1. >>> f = ContactForm(data)
  2. >>> print(f.as_table())
  3. <tr class="required"><th><label class="required" for="id_subject">Subject:</label> ...
  4. <tr class="required"><th><label class="required" for="id_message">Message:</label> ...
  5. <tr class="required error"><th><label class="required" for="id_sender">Sender:</label> ...
  6. <tr><th><label for="id_cc_myself">Cc myself:<label> ...
  7. >>> f['subject'].label_tag()
  8. <label class="required" for="id_subject">Subject:</label>
  9. >>> f['subject'].label_tag(attrs={'class': 'foo'})
  10. <label for="id_subject" class="foo required">Subject:</label>

Configuring form elements’ HTML id attributes and <label> tags

  • Form.auto_id
  • By default, the form rendering methods include:

  • HTML id attributes on the form elements.

  • The corresponding <label> tags around the labels. An HTML <label> tagdesignates which label text is associated with which form element. This smallenhancement makes forms more usable and more accessible to assistive devices.It’s always a good idea to use <label> tags.The id attribute values are generated by prepending id_ to the formfield names. This behavior is configurable, though, if you want to change theid convention or remove HTML id attributes and <label> tagsentirely.

Use the auto_id argument to the Form constructor to control the idand label behavior. This argument must be True, False or a string.

If auto_id is False, then the form output will not include <label>tags nor id attributes:

  1. >>> f = ContactForm(auto_id=False)
  2. >>> print(f.as_table())
  3. <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required></td></tr>
  4. <tr><th>Message:</th><td><input type="text" name="message" required></td></tr>
  5. <tr><th>Sender:</th><td><input type="email" name="sender" required></td></tr>
  6. <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself"></td></tr>
  7. >>> print(f.as_ul())
  8. <li>Subject: <input type="text" name="subject" maxlength="100" required></li>
  9. <li>Message: <input type="text" name="message" required></li>
  10. <li>Sender: <input type="email" name="sender" required></li>
  11. <li>Cc myself: <input type="checkbox" name="cc_myself"></li>
  12. >>> print(f.as_p())
  13. <p>Subject: <input type="text" name="subject" maxlength="100" required></p>
  14. <p>Message: <input type="text" name="message" required></p>
  15. <p>Sender: <input type="email" name="sender" required></p>
  16. <p>Cc myself: <input type="checkbox" name="cc_myself"></p>

If autoid is set to True, then the form output _will include<label> tags and will use the field name as its id for each formfield:

  1. >>> f = ContactForm(auto_id=True)
  2. >>> print(f.as_table())
  3. <tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" required></td></tr>
  4. <tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" required></td></tr>
  5. <tr><th><label for="sender">Sender:</label></th><td><input type="email" name="sender" id="sender" required></td></tr>
  6. <tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself"></td></tr>
  7. >>> print(f.as_ul())
  8. <li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" required></li>
  9. <li><label for="message">Message:</label> <input type="text" name="message" id="message" required></li>
  10. <li><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" required></li>
  11. <li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself"></li>
  12. >>> print(f.as_p())
  13. <p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" required></p>
  14. <p><label for="message">Message:</label> <input type="text" name="message" id="message" required></p>
  15. <p><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" required></p>
  16. <p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself"></p>

If autoid is set to a string containing the format character '%s',then the form output will include <label> tags, and will generate idattributes based on the format string. For example, for a format string'field%s', a field named subject will get the id value'field_subject'. Continuing our example:

  1. >>> f = ContactForm(auto_id='id_for_%s')
  2. >>> print(f.as_table())
  3. <tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" required></td></tr>
  4. <tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" required></td></tr>
  5. <tr><th><label for="id_for_sender">Sender:</label></th><td><input type="email" name="sender" id="id_for_sender" required></td></tr>
  6. <tr><th><label for="id_for_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></td></tr>
  7. >>> print(f.as_ul())
  8. <li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></li>
  9. <li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" required></li>
  10. <li><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" required></li>
  11. <li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></li>
  12. >>> print(f.as_p())
  13. <p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></p>
  14. <p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" required></p>
  15. <p><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" required></p>
  16. <p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></p>

If auto_id is set to any other true value – such as a string that doesn’tinclude %s – then the library will act as if auto_id is True.

By default, autoid is set to the string 'id%s'.

  • Form.label_suffix
  • A translatable string (defaults to a colon (:) in English) that will beappended after any label name when a form is rendered.

It’s possible to customize that character, or omit it entirely, using thelabel_suffix parameter:

  1. >>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
  2. >>> print(f.as_ul())
  3. <li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></li>
  4. <li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" required></li>
  5. <li><label for="id_for_sender">Sender</label> <input type="email" name="sender" id="id_for_sender" required></li>
  6. <li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></li>
  7. >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
  8. >>> print(f.as_ul())
  9. <li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></li>
  10. <li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" required></li>
  11. <li><label for="id_for_sender">Sender -></label> <input type="email" name="sender" id="id_for_sender" required></li>
  12. <li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></li>

Note that the label suffix is added only if the last character of thelabel isn’t a punctuation character (in English, those are ., !, ?or :).

Fields can also define their own label_suffix.This will take precedence over Form.label_suffix. The suffix can also be overridden at runtimeusing the label_suffix parameter tolabel_tag().

  • Form.use_required_attribute
  • When set to True (the default), required form fields will have therequired HTML attribute.

Formsets instantiate forms withuse_required_attribute=False to avoid incorrect browser validation whenadding and deleting forms from a formset.

Configuring the rendering of a form’s widgets

  • Form.default_renderer
  • Specifies the renderer to use for the form. Defaults toNone which means to use the default renderer specified by theFORM_RENDERER setting.

You can set this as a class attribute when declaring your form or use therenderer argument to Form.init(). For example:

  1. from django import forms
  2.  
  3. class MyForm(forms.Form):
  4. default_renderer = MyRenderer()

or:

  1. form = MyForm(renderer=MyRenderer())

Notes on field ordering

In the as_p(), as_ul() and as_table() shortcuts, the fields aredisplayed in the order in which you define them in your form class. Forexample, in the ContactForm example, the fields are defined in the ordersubject, message, sender, cc_myself. To reorder the HTMLoutput, change the order in which those fields are listed in the class.

There are several other ways to customize the order:

  • Form.field_order
  • By default Form.field_order=None, which retains the order in which youdefine the fields in your form class. If field_order is a list of fieldnames, the fields are ordered as specified by the list and remaining fields areappended according to the default order. Unknown field names in the list areignored. This makes it possible to disable a field in a subclass by setting itto None without having to redefine ordering.

You can also use the Form.fieldorder argument to a Form tooverride the field order. If a Form definesfield_order_and you include field_order when instantiatingthe Form, then the latter field_order will have precedence.

  • Form.orderfields(_field_order)
  • You may rearrange the fields any time using order_fields() with a list offield names as in field_order.

How errors are displayed

If you render a bound Form object, the act of rendering will automaticallyrun the form’s validation if it hasn’t already happened, and the HTML outputwill include the validation errors as a <ul class="errorlist"> near thefield. The particular positioning of the error messages depends on the outputmethod you’re using:

  1. >>> data = {'subject': '',
  2. ... 'message': 'Hi there',
  3. ... 'sender': 'invalid email address',
  4. ... 'cc_myself': True}
  5. >>> f = ContactForm(data, auto_id=False)
  6. >>> print(f.as_table())
  7. <tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" required></td></tr>
  8. <tr><th>Message:</th><td><input type="text" name="message" value="Hi there" required></td></tr>
  9. <tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid email address.</li></ul><input type="email" name="sender" value="invalid email address" required></td></tr>
  10. <tr><th>Cc myself:</th><td><input checked type="checkbox" name="cc_myself"></td></tr>
  11. >>> print(f.as_ul())
  12. <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" required></li>
  13. <li>Message: <input type="text" name="message" value="Hi there" required></li>
  14. <li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input type="email" name="sender" value="invalid email address" required></li>
  15. <li>Cc myself: <input checked type="checkbox" name="cc_myself"></li>
  16. >>> print(f.as_p())
  17. <p><ul class="errorlist"><li>This field is required.</li></ul></p>
  18. <p>Subject: <input type="text" name="subject" maxlength="100" required></p>
  19. <p>Message: <input type="text" name="message" value="Hi there" required></p>
  20. <p><ul class="errorlist"><li>Enter a valid email address.</li></ul></p>
  21. <p>Sender: <input type="email" name="sender" value="invalid email address" required></p>
  22. <p>Cc myself: <input checked type="checkbox" name="cc_myself"></p>

Customizing the error list format

By default, forms use django.forms.utils.ErrorList to format validationerrors. If you’d like to use an alternate class for displaying errors, you canpass that in at construction time:

  1. >>> from django.forms.utils import ErrorList
  2. >>> class DivErrorList(ErrorList):
  3. ... def __str__(self):
  4. ... return self.as_divs()
  5. ... def as_divs(self):
  6. ... if not self: return ''
  7. ... return '<div class="errorlist">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self])
  8. >>> f = ContactForm(data, auto_id=False, error_class=DivErrorList)
  9. >>> f.as_p()
  10. <div class="errorlist"><div class="error">This field is required.</div></div>
  11. <p>Subject: <input type="text" name="subject" maxlength="100" required></p>
  12. <p>Message: <input type="text" name="message" value="Hi there" required></p>
  13. <div class="errorlist"><div class="error">Enter a valid email address.</div></div>
  14. <p>Sender: <input type="email" name="sender" value="invalid email address" required></p>
  15. <p>Cc myself: <input checked type="checkbox" name="cc_myself"></p>

More granular output

The as_p(), as_ul(), and as_table() methods are shortcuts –they’re not the only way a form object can be displayed.

  • class BoundField
  • Used to display HTML or access attributes for a single field of aForm instance.

The str() method of this object displays the HTML for this field.

To retrieve a single BoundField, use dictionary lookup syntax on your formusing the field’s name as the key:

  1. >>> form = ContactForm()
  2. >>> print(form['subject'])
  3. <input id="id_subject" type="text" name="subject" maxlength="100" required>

To retrieve all BoundField objects, iterate the form:

  1. >>> form = ContactForm()
  2. >>> for boundfield in form: print(boundfield)
  3. <input id="id_subject" type="text" name="subject" maxlength="100" required>
  4. <input type="text" name="message" id="id_message" required>
  5. <input type="email" name="sender" id="id_sender" required>
  6. <input type="checkbox" name="cc_myself" id="id_cc_myself">

The field-specific output honors the form object’s auto_id setting:

  1. >>> f = ContactForm(auto_id=False)
  2. >>> print(f['message'])
  3. <input type="text" name="message" required>
  4. >>> f = ContactForm(auto_id='id_%s')
  5. >>> print(f['message'])
  6. <input type="text" name="message" id="id_message" required>

Attributes of BoundField

  • BoundField.auto_id
  • The HTML ID attribute for this BoundField. Returns an empty stringif Form.auto_id is False.

  • BoundField.data

  • This property returns the data for this BoundFieldextracted by the widget’s value_from_datadict()method, or None if it wasn’t given:
  1. >>> unbound_form = ContactForm()
  2. >>> print(unbound_form['subject'].data)
  3. None
  4. >>> bound_form = ContactForm(data={'subject': 'My Subject'})
  5. >>> print(bound_form['subject'].data)
  6. My Subject
  • BoundField.errors
  • A list-like object that is displayedas an HTML <ul class="errorlist"> when printed:
  1. >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
  2. >>> f = ContactForm(data, auto_id=False)
  3. >>> print(f['message'])
  4. <input type="text" name="message" required>
  5. >>> f['message'].errors
  6. ['This field is required.']
  7. >>> print(f['message'].errors)
  8. <ul class="errorlist"><li>This field is required.</li></ul>
  9. >>> f['subject'].errors
  10. []
  11. >>> print(f['subject'].errors)
  12.  
  13. >>> str(f['subject'].errors)
  14. ''
  • BoundField.field
  • The form Field instance from the form class thatthis BoundField wraps.

  • BoundField.form

  • The Form instance this BoundFieldis bound to.

  • BoundField.help_text

  • The help_text of the field.

  • BoundField.html_name

  • The name that will be used in the widget’s HTML name attribute. It takesthe form prefix into account.

  • BoundField.id_for_label

  • Use this property to render the ID of this field. For example, if you aremanually constructing a <label> in your template (despite the fact thatlabel_tag() will do this for you):
  1. <label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }}

By default, this will be the field’s name prefixed by id_(“id_my_field” for the example above). You may modify the ID by settingattrs on the field’s widget. For example,declaring a field like this:

my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'}))

and using the template above, would render something like:

<label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" required>
  • BoundField.is_hidden
  • Returns True if this BoundField’s widget ishidden.

  • BoundField.label

  • The label of the field. This is used inlabel_tag().

  • BoundField.name

  • The name of this field in the form:
>>> f = ContactForm()
>>> print(f['subject'].name)
subject
>>> print(f['message'].name)
message

Methods of BoundField

  • BoundField.ashidden(_attrs=None, **kwargs)
  • Returns a string of HTML for representing this as an <input type="hidden">.

**kwargs are passed to as_widget().

This method is primarily used internally. You should use a widget instead.

  • BoundField.aswidget(_widget=None, attrs=None, only_initial=False)
  • Renders the field by rendering the passed widget, adding any HTMLattributes passed as attrs. If no widget is specified, then thefield’s default widget will be used.

only_initial is used by Django internals and should not be setexplicitly.

  • BoundField.css_classes()
  • When you use Django’s rendering shortcuts, CSS classes are used toindicate required form fields or fields that contain errors. If you’remanually rendering a form, you can access these CSS classes using thecss_classes method:
>>> f = ContactForm(data={'message': ''})
>>> f['message'].css_classes()
'required'

If you want to provide some additional classes in addition to theerror and required classes that may be required, you can providethose classes as an argument:

>>> f = ContactForm(data={'message': ''})
>>> f['message'].css_classes('foo bar')
'foo bar required'
  • BoundField.labeltag(_contents=None, attrs=None, label_suffix=None)
  • To separately render the label tag of a form field, you can call itslabel_tag() method:
>>> f = ContactForm(data={'message': ''})
>>> print(f['message'].label_tag())
<label for="id_message">Message:</label>

You can provide the contents parameter which will replace theauto-generated label tag. An attrs dictionary may contain additionalattributes for the <label> tag.

The HTML that’s generated includes the form’slabel_suffix (a colon, by default) or, if set, thecurrent field’s label_suffix. The optionallabel_suffix parameter allows you to override any previously setsuffix. For example, you can use an empty string to hide the label on selectedfields. If you need to do this in a template, you could write a customfilter to allow passing parameters to label_tag.

  • BoundField.value()
  • Use this method to render the raw value of this field as it would be renderedby a Widget:
>>> initial = {'subject': 'welcome'}
>>> unbound_form = ContactForm(initial=initial)
>>> bound_form = ContactForm(data={'subject': 'hi'}, initial=initial)
>>> print(unbound_form['subject'].value())
welcome
>>> print(bound_form['subject'].value())
hi

Customizing BoundField

If you need to access some additional information about a form field in atemplate and using a subclass of Field isn’tsufficient, consider also customizing BoundField.

A custom form field can override get_bound_field():

  • Field.getbound_field(_form, field_name)
  • Takes an instance of Form and the name of the field.The return value will be used when accessing the field in a template. Mostlikely it will be an instance of a subclass ofBoundField.

If you have a GPSCoordinatesField, for example, and want to be able toaccess additional information about the coordinates in a template, this couldbe implemented as follows:

class GPSCoordinatesBoundField(BoundField):
    @property
    def country(self):
        """
        Return the country the coordinates lie in or None if it can't be
        determined.
        """
        value = self.value()
        if value:
            return get_country_from_coordinates(value)
        else:
            return None

class GPSCoordinatesField(Field):
    def get_bound_field(self, form, field_name):
        return GPSCoordinatesBoundField(form, self, field_name)

Now you can access the country in a template with{{ form.coordinates.country }}.

Binding uploaded files to a form

Dealing with forms that have FileField and ImageField fieldsis a little more complicated than a normal form.

Firstly, in order to upload files, you’ll need to make sure that your<form> element correctly defines the enctype as"multipart/form-data":

<form enctype="multipart/form-data" method="post" action="/foo/">

Secondly, when you use the form, you need to bind the file data. Filedata is handled separately to normal form data, so when your formcontains a FileField and ImageField, you will need to specifya second argument when you bind your form. So if we extend ourContactForm to include an ImageField called mugshot, weneed to bind the file data containing the mugshot image:

# Bound form with an image field
>>> from django.core.files.uploadedfile import SimpleUploadedFile
>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)}
>>> f = ContactFormWithMugshot(data, file_data)

In practice, you will usually specify request.FILES as the sourceof file data (just like you use request.POST as the source ofform data):

# Bound form with an image field, data from the request
>>> f = ContactFormWithMugshot(request.POST, request.FILES)

Constructing an unbound form is the same as always – omit both form data _and_file data:

# Unbound form with an image field
>>> f = ContactFormWithMugshot()

Testing for multipart forms

  • Form.is_multipart()
  • If you’re writing reusable views or templates, you may not know ahead of timewhether your form is a multipart form or not. The is_multipart() methodtells you whether the form requires multipart encoding for submission:
>>> f = ContactFormWithMugshot()
>>> f.is_multipart()
True

Here’s an example of how you might use this in a template:

{% if form.is_multipart %}
    <form enctype="multipart/form-data" method="post" action="/foo/">
{% else %}
    <form method="post" action="/foo/">
{% endif %}
{{ form }}
</form>

Subclassing forms

If you have multiple Form classes that share fields, you can usesubclassing to remove redundancy.

When you subclass a custom Form class, the resulting subclass willinclude all fields of the parent class(es), followed by the fields you definein the subclass.

In this example, ContactFormWithPriority contains all the fields fromContactForm, plus an additional field, priority. The ContactFormfields are ordered first:

>>> class ContactFormWithPriority(ContactForm):
...     priority = forms.CharField()
>>> f = ContactFormWithPriority(auto_id=False)
>>> print(f.as_ul())
<li>Subject: <input type="text" name="subject" maxlength="100" required></li>
<li>Message: <input type="text" name="message" required></li>
<li>Sender: <input type="email" name="sender" required></li>
<li>Cc myself: <input type="checkbox" name="cc_myself"></li>
<li>Priority: <input type="text" name="priority" required></li>

It’s possible to subclass multiple forms, treating forms as mixins. In thisexample, BeatleForm subclasses both PersonForm and InstrumentForm(in that order), and its field list includes the fields from the parentclasses:

>>> from django import forms
>>> class PersonForm(forms.Form):
...     first_name = forms.CharField()
...     last_name = forms.CharField()
>>> class InstrumentForm(forms.Form):
...     instrument = forms.CharField()
>>> class BeatleForm(InstrumentForm, PersonForm):
...     haircut_type = forms.CharField()
>>> b = BeatleForm(auto_id=False)
>>> print(b.as_ul())
<li>First name: <input type="text" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Instrument: <input type="text" name="instrument" required></li>
<li>Haircut type: <input type="text" name="haircut_type" required></li>

It’s possible to declaratively remove a Field inherited from a parent classby setting the name of the field to None on the subclass. For example:

>>> from django import forms

>>> class ParentForm(forms.Form):
...     name = forms.CharField()
...     age = forms.IntegerField()

>>> class ChildForm(ParentForm):
...     name = None

>>> list(ChildForm().fields)
['age']

Prefixes for forms

  • Form.prefix
  • You can put several Django forms inside one <form> tag. To give eachForm its own namespace, use the prefix keyword argument:
>>> mother = PersonForm(prefix="mother")
>>> father = PersonForm(prefix="father")
>>> print(mother.as_ul())
<li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" required></li>
<li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" required></li>
>>> print(father.as_ul())
<li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" required></li>
<li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" required></li>

The prefix can also be specified on the form class:

>>> class PersonForm(forms.Form):
...     ...
...     prefix = 'person'