The Forms API¶
About this document
This document covers the gritty details of Django’s forms API. You shouldread theintroduction to working with formsfirst.
Bound and unbound forms¶
AForm instance is eitherbound to a set of data, orunbound.
If it’sbound 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’sunbound, it cannot do validation (because there’s no data tovalidate!), but it can still render the blank form as HTML.
To create an unboundForm instance, instantiate the class:
>>>f=ContactForm()
To bind data to a form, pass the data as a dictionary as the first parameter toyourForm class constructor:
>>>data={..."subject":"hello",..."message":"Hi there",..."sender":"foo@example.com",..."cc_myself":True,...}>>>f=ContactForm(data)
In this dictionary, the keys are the field names, which correspond to theattributes in yourForm 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 theField, 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’sis_bound attribute:
>>>f=ContactForm()>>>f.is_boundFalse>>>f=ContactForm({"subject":"hello"})>>>f.is_boundTrue
Note that passing an empty dictionary creates abound form with empty data:
>>>f=ContactForm({})>>>f.is_boundTrue
If you have a boundForm instance and want to change the data somehow,or if you want to bind an unboundForm instance to some data, createanotherForm instance. There is no way to change data in aForm instance. Once aForm instance has been created, youshould consider its data immutable, whether it has data or not.
Using forms to validate data¶
- Form.clean()¶
Implement aclean() method on yourForm 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 aForm object is to validate data. With a boundForm instance, call theis_valid() method to run validationand return a boolean designating whether the data was valid:
>>>data={..."subject":"hello",..."message":"Hi there",..."sender":"foo@example.com",..."cc_myself":True,...}>>>f=ContactForm(data)>>>f.is_valid()True
Let’s try with some invalid data. In this case,subject is blank (an error,because all fields are required by default) andsender is not a validemail address:
>>>data={..."subject":"",..."message":"Hi there",..."sender":"invalid email address",..."cc_myself":True,...}>>>f=ContactForm(data)>>>f.is_valid()False
- Form.errors¶
Access theerrors attribute to get a dictionary of errormessages:
>>>f.errors{'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 accesserrors without having to callis_valid() first. The form’s data will be validated the first timeeither you callis_valid() or accesserrors.
The validation routines will only get called once, regardless of how many timesyou accesserrors or callis_valid(). This means thatif validation has side effects, those side effects will only be triggered once.
- Form.errors.as_data()¶
Returns adict that maps fields to their originalValidationErrorinstances.
>>>f.errors.as_data(){'sender': [ValidationError(['Enter a valid email address.'])],'subject': [ValidationError(['This field is required.'])]}
Use this method anytime you need to identify an error by itscode. 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 onas_data().
The need for theas_data() method is due to backwards compatibility.PreviouslyValidationError instances were lost as soon as theirrendered error messages were added to theForm.errors dictionary.IdeallyForm.errors would have storedValidationError instancesand methods with anas_ prefix could render them, but it had to be donethe other way around in order not to break code that expects rendered errormessages inForm.errors.
- Form.errors.as_json(escape_html=False)¶
Returns the errors serialized as JSON.
>>>f.errors.as_json(){"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],"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 withelement.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 alsosetescape_html=True and error messages will be escaped so you can use themdirectly in HTML.
- Form.errors.get_json_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.
Theescape_html parameter behaves as described inForm.errors.as_json().
- Form.add_error(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.
Thefield argument is the name of the field to which the errorsshould be added. If its value isNone the error will be treated asa non-field error as returned byForm.non_field_errors().
Theerror argument can be a string, or preferably an instance ofValidationError. SeeRaising ValidationError for best practiceswhen defining form errors.
Note thatForm.add_error() automatically removes the relevant field fromcleaned_data.
- Form.has_error(field,code=None)¶
This method returns a boolean designating whether a field has an error witha specific errorcode. Ifcode isNone, it will returnTrueif the field contains any errors at all.
To check for non-field errors useNON_FIELD_ERRORS as thefield parameter.
- Form.non_field_errors()¶
This method returns the list of errors fromForm.errors that aren’t associated with a particular field.This includesValidationErrors that are raised inForm.clean() and errors added usingForm.add_error(None,"...").
Behavior of unbound forms¶
It’s meaningless to validate a form with no data, but, for the record, here’swhat happens with unbound forms:
>>>f=ContactForm()>>>f.is_valid()False>>>f.errors{}
Initial form values¶
- Form.initial¶
Useinitial to declare the initial value of form fields atruntime. For example, you might want to fill in ausername field with theusername of the current session.
To accomplish this, use theinitial argument to aForm.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:
>>>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 aField definesinitialand youincludeinitial when instantiating theForm, 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:
>>>fromdjangoimportforms>>>classCommentForm(forms.Form):...name=forms.CharField(initial="class")...url=forms.URLField()...comment=forms.CharField()...>>>f=CommentForm(initial={"name":"instance"},auto_id=False)>>>print(f)<div>Name:<input type="text" name="name" value="instance" required></div><div>Url:<input type="url" name="url" required></div><div>Comment:<input type="text" name="comment" required></div>
- Form.get_initial_for_field(field,field_name)¶
Returns the initial data for a form field. It retrieves the data fromForm.initial if present, otherwise tryingField.initial.Callable values are evaluated.
It is recommended to useBoundField.initial overget_initial_for_field() becauseBoundField.initial has asimpler interface. Also, unlikeget_initial_for_field(),BoundField.initial caches its values. This is useful especially whendealing with callables whose return values can change (e.g.datetime.now oruuid.uuid4):
>>>importuuid>>>classUUIDCommentForm(CommentForm):...identifier=forms.UUIDField(initial=uuid.uuid4)...>>>f=UUIDCommentForm()>>>f.get_initial_for_field(f.fields["identifier"],"identifier")UUID('972ca9e4-7bfe-4f5b-af7d-07b3aa306334')>>>f.get_initial_for_field(f.fields["identifier"],"identifier")UUID('1b411fab-844e-4dec-bd4f-e9b0495f04d0')>>># Using BoundField.initial, for comparison>>>f["identifier"].initialUUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')>>>f["identifier"].initialUUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
Checking which form data has changed¶
- Form.has_changed()¶
Use thehas_changed() method on yourForm when you need to check if theform data has been changed from the initial data.
>>>data={..."subject":"hello",..."message":"Hi there",..."sender":"foo@example.com",..."cc_myself":True,...}>>>f=ContactForm(data,initial=data)>>>f.has_changed()False
When the form is submitted, we reconstruct it and provide the original dataso that the comparison can be done:
>>>f=ContactForm(request.POST,initial=data)>>>f.has_changed()
has_changed() will beTrue if the data fromrequest.POST differsfrom what was provided ininitial orFalse otherwise. Theresult is computed by callingField.has_changed() for each field in theform.
- Form.changed_data¶
Thechanged_data attribute returns a list of the names of the fields whosevalues in the form’s bound data (usuallyrequest.POST) differ from what wasprovided ininitial. It returns an empty list if no data differs.
>>>f=ContactForm(request.POST,initial=data)>>>iff.has_changed():...print("The following fields changed:%s"%", ".join(f.changed_data))...>>>f.changed_data['subject', 'message']
Accessing the fields from the form¶
- Form.fields¶
You can access the fields ofForm instance from itsfieldsattribute:
>>>forrowinf.fields.values():...print(row)...<django.forms.fields.CharField object at 0x7ffaac632510><django.forms.fields.URLField object at 0x7ffaac632f90><django.forms.fields.CharField object at 0x7ffaac3aa050>>>>f.fields["name"]<django.forms.fields.CharField object at 0x7ffaac6324d0>
You can alter the field andBoundField ofForm instance tochange the way it is presented in the form:
>>>f.as_div().split("</div>")[0]'<div><label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_subject">'>>>f["subject"].label="Topic">>>f.as_div().split("</div>")[0]'<div><label for="id_subject">Topic:</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
Beware not to alter thebase_fields attribute because this modificationwill influence all subsequentContactForm instances within the same Pythonprocess:
>>>f.base_fields["subject"].label_suffix="?">>>another_f=CommentForm(auto_id=False)>>>f.as_div().split("</div>")[0]'<div><label for="id_subject">Subject?</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
Accessing “clean” data¶
- Form.cleaned_data¶
Each field in aForm 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 aPythondatetime.date object. Regardless of whether you pass it a string inthe format'1994-07-15', adatetime.date object, or a number of otherformats,DateField will always normalize it to adatetime.date objectas long as it’s valid.
Once you’ve created aForm instance with a set of data and validatedit, you can access the clean data via itscleaned_data attribute:
>>>data={..."subject":"hello",..."message":"Hi there",..."sender":"foo@example.com",..."cc_myself":True,...}>>>f=ContactForm(data)>>>f.is_valid()True>>>f.cleaned_data{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
Note that any text-based field – such asCharField orEmailField –always cleans the input into a string. We’ll cover the encoding implicationslater in this document.
If your data doesnot validate, thecleaned_data dictionary containsonly the valid fields:
>>>data={..."subject":"",..."message":"Hi there",..."sender":"invalid email address",..."cc_myself":True,...}>>>f=ContactForm(data)>>>f.is_valid()False>>>f.cleaned_data{'cc_myself': True, 'message': 'Hi there'}
cleaned_data will alwaysonly contain a key for fields defined in theForm, even if you pass extra data when you define theForm. In thisexample, we pass a bunch of extra fields to theContactForm constructor,butcleaned_data contains only the form’s fields:
>>>data={..."subject":"hello",..."message":"Hi there",..."sender":"foo@example.com",..."cc_myself":True,..."extra_field_1":"foo",..."extra_field_2":"bar",..."extra_field_3":"baz",...}>>>f=ContactForm(data)>>>f.is_valid()True>>>f.cleaned_data# Doesn't contain extra_field_1, etc.{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
When theForm is valid,cleaned_data will include a key and value forall 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, butcleaned_data includes it, with an empty value:
>>>fromdjangoimportforms>>>classOptionalPersonForm(forms.Form):...first_name=forms.CharField()...last_name=forms.CharField()...nick_name=forms.CharField(required=False)...>>>data={"first_name":"John","last_name":"Lennon"}>>>f=OptionalPersonForm(data)>>>f.is_valid()True>>>f.cleaned_data{'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}
In this above example, thecleaned_data value fornick_name is set to anempty string, becausenick_name isCharField, andCharFields treatempty values as an empty string. Each field type knows what its “blank” valueis – e.g., forDateField, it’sNone 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-inField 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 inForm and field validation.
Outputting forms as HTML¶
The second task of aForm object is to render itself as HTML. To do so,print it:
>>>f=ContactForm()>>>print(f)<div><label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_subject"></div><div><label for="id_message">Message:</label><input type="text" name="message" required id="id_message"></div><div><label for="id_sender">Sender:</label><input type="email" name="sender" required id="id_sender"></div><div><label for="id_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_cc_myself"></div>
If the form is bound to data, the HTML output will include that dataappropriately. For example, if a field is represented by an<inputtype="text">, the data will be in thevalue attribute. If afield is represented by an<inputtype="checkbox">, then that HTML willincludechecked if appropriate:
>>>data={..."subject":"hello",..."message":"Hi there",..."sender":"foo@example.com",..."cc_myself":True,...}>>>f=ContactForm(data)>>>print(f)<div><label for="id_subject">Subject:</label><input type="text" name="subject" value="hello" maxlength="100" required id="id_subject"></div><div><label for="id_message">Message:</label><input type="text" name="message" value="Hi there" required id="id_message"></div><div><label for="id_sender">Sender:</label><input type="email" name="sender" value="foo@example.com" required id="id_sender"></div><div><label for="id_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_cc_myself" checked></div>
This default output wraps each field with a<div>. Notice the following:
For flexibility, the output doesnot include the
<form>and</form>tags or an<inputtype="submit">tag. It’s your job to do that.Each field type has a default HTML representation.
CharFieldisrepresented by an<inputtype="text">andEmailFieldby an<inputtype="email">.BooleanField(null=False)is represented by an<inputtype="checkbox">. Note these are merely sensible defaults; you canspecify which HTML to use for a given field by using widgets, which we’llexplain shortly.The HTML
namefor each tag is taken directly from its attribute namein theContactFormclass.The text label for each field – e.g.
'Subject:','Message:'and'Ccmyself:'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 itsid. Itsid, in turn, isgenerated by prepending'id_'to the field name. Theidattributes 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
<!DOCTYPEhtml>. For example,it uses boolean attributes such ascheckedrather than the XHTML styleofchecked='checked'.
Although<div> output is the default output style when youprint a formyou can customize the output by using your own form template which can be setsite-wide, per-form, or per-instance. SeeReusable form templates.
Default rendering¶
The default rendering when youprint a form uses the following methods andattributes.
template_name¶
- Form.template_name¶
The name of the template rendered if the form is cast into a string, e.g. viaprint(form) or in a template via{{form}}.
By default, a property returning the value of the renderer’sform_template_name. You may set itas a string template name in order to override that for a particular formclass.
render()¶
- Form.render(template_name=None,context=None,renderer=None)¶
The render method is called by__str__ as well as theForm.as_div(),Form.as_table(),Form.as_p(), andForm.as_ul() methods.All arguments are optional and default to:
template_name:Form.template_namecontext: Value returned byForm.get_context()renderer: Value returned byForm.default_renderer
By passingtemplate_name you can customize the template used for just asingle call.
get_context()¶
- Form.get_context()¶
Return the template context for rendering the form.
The available context is:
form: The bound form.fields: All bound fields, except the hidden fields.hidden_fields: All hidden bound fields.errors: All non field related or hidden field related form errors.
template_name_label¶
- Form.template_name_label¶
The template used to render a field’s<label>, used when callingBoundField.label_tag()/legend_tag(). Can be changed perform by overriding this attribute or more generally by overriding the defaulttemplate, see alsoOverriding built-in form templates.
Output styles¶
The recommended approach for changing form output style is to set a custom formtemplate either site-wide, per-form, or per-instance. SeeReusable form templates for examples.
The following helper functions are provided for backward compatibility and area proxy toForm.render() passing a particulartemplate_name value.
Note
Of the framework provided templates and output styles, the defaultas_div() is recommended over theas_p(),as_table(), andas_ul() versions as the template implements<fieldset> and<legend> to group related inputs and is easier for screen reader usersto navigate.
Each helper pairs a form method with an attribute giving the appropriatetemplate name.
as_div()¶
- Form.template_name_div¶
The template used byas_div(). Default:'django/forms/div.html'.
- Form.as_div()¶
as_div() renders the form as a series of<div> elements, with each<div> containing one field, such as:
>>>f=ContactForm()>>>f.as_div()
… gives HTML like:
<div><labelfor="id_subject">Subject:</label><inputtype="text"name="subject"maxlength="100"requiredid="id_subject"></div><div><labelfor="id_message">Message:</label><inputtype="text"name="message"requiredid="id_message"></div><div><labelfor="id_sender">Sender:</label><inputtype="email"name="sender"requiredid="id_sender"></div><div><labelfor="id_cc_myself">Cc myself:</label><inputtype="checkbox"name="cc_myself"id="id_cc_myself"></div>
as_p()¶
- Form.template_name_p¶
The template used byas_p(). Default:'django/forms/p.html'.
- Form.as_p()¶
as_p() renders the form as a series of<p> tags, with each<p>containing one field:
>>>f=ContactForm()>>>f.as_p()'<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>'>>>print(f.as_p())<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p><p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p><p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></p><p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>
as_ul()¶
- Form.template_name_ul¶
The template used byas_ul(). Default:'django/forms/ul.html'.
- Form.as_ul()¶
as_ul() renders the form as a series of<li> tags, with each<li>containing one field. It doesnot include the<ul> or</ul>, so thatyou can specify any HTML attributes on the<ul> for flexibility:
>>>f=ContactForm()>>>f.as_ul()'<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>'>>>print(f.as_ul())<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li><li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li><li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li><li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>
as_table()¶
- Form.template_name_table¶
The template used byas_table(). Default:'django/forms/table.html'.
- Form.as_table()¶
as_table() renders the form as an HTML<table>:
>>>f=ContactForm()>>>f.as_table()'<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>'>>>print(f)<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr><tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr><tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr><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.
TheForm class has a couple of hooks you can use to addclassattributes to required rows or to rows with errors: set theForm.error_css_class and/orForm.required_css_classattributes:
fromdjangoimportformsclassContactForm(forms.Form):error_css_class="error"required_css_class="required"# ... 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:
>>>f=ContactForm(data)>>>print(f)<div class="required"><label for="id_subject" class="required">Subject:</label> ...<div class="required"><label for="id_message" class="required">Message:</label> ...<div class="required"><label for="id_sender" class="required">Sender:</label> ...<div><label for="id_cc_myself">Cc myself:</label> ...>>>f["subject"].label_tag()<label class="required" for="id_subject">Subject:</label>>>>f["subject"].legend_tag()<legend class="required" for="id_subject">Subject:</legend>>>>f["subject"].label_tag(attrs={"class":"foo"})<label for="id_subject" class="foo required">Subject:</label>>>>f["subject"].legend_tag(attrs={"class":"foo"})<legend for="id_subject" class="foo required">Subject:</legend>
Configuring form elements’ HTMLid attributes and<label> tags¶
- Form.auto_id¶
By default, the form rendering methods include:
HTML
idattributes 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.
Theid attribute values are generated by prependingid_ to the formfield names. This behavior is configurable, though, if you want to change theid convention or remove HTMLid attributes and<label> tagsentirely.
Use theauto_id argument to theForm constructor to control theidand label behavior. This argument must beTrue,False or a string.
Ifauto_id isFalse, then the form output will not include<label>tags norid attributes:
>>>f=ContactForm(auto_id=False)>>>print(f)<div>Subject:<input type="text" name="subject" maxlength="100" required></div><div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div><div>Sender:<input type="email" name="sender" required></div><div>Cc myself:<input type="checkbox" name="cc_myself"></div>
Ifauto_id is set toTrue, then the form outputwill include<label> tags and will use the field name as itsid for each formfield:
>>>f=ContactForm(auto_id=True)>>>print(f)<div><label for="subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="subject"></div><div><label for="message">Message:</label><textarea name="message" cols="40" rows="10" required id="message"></textarea></div><div><label for="sender">Sender:</label><input type="email" name="sender" required id="sender"></div><div><label for="cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="cc_myself"></div>
Ifauto_id is set to a string containing the format character'%s',then the form output will include<label> tags, and will generateidattributes based on the format string. For example, for a format string'field_%s', a field namedsubject will get theid value'field_subject'. Continuing our example:
>>>f=ContactForm(auto_id="id_for_%s")>>>print(f)<div><label for="id_for_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div><div><label for="id_for_message">Message:</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div><div><label for="id_for_sender">Sender:</label><input type="email" name="sender" required id="id_for_sender"></div><div><label for="id_for_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>
Ifauto_id is set to any other true value – such as a string that doesn’tinclude%s – then the library will act as ifauto_id isTrue.
By default,auto_id 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:
>>>f=ContactForm(auto_id="id_for_%s",label_suffix="")>>>print(f)<div><label for="id_for_subject">Subject</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div><div><label for="id_for_message">Message</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div><div><label for="id_for_sender">Sender</label><input type="email" name="sender" required id="id_for_sender"></div><div><label for="id_for_cc_myself">Cc myself</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>>>>f=ContactForm(auto_id="id_for_%s",label_suffix=" ->")>>>print(f)<div><label for="id_for_subject">Subject -></label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div><div><label for="id_for_message">Message -></label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div><div><label for="id_for_sender">Sender -></label><input type="email" name="sender" required id="id_for_sender"></div><div><label for="id_for_cc_myself">Cc myself -></label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>
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 ownlabel_suffix.This will take precedence overForm.label_suffix. The suffix can also be overridden at runtimeusing thelabel_suffix parameter tolabel_tag()/legend_tag().
- Form.use_required_attribute¶
When set toTrue (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 therenderer 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 toForm.__init__(). For example:
fromdjangoimportformsclassMyForm(forms.Form):default_renderer=MyRenderer()
or:
form=MyForm(renderer=MyRenderer())
Notes on field ordering¶
In theas_p(),as_ul() andas_table() shortcuts, the fields aredisplayed in the order in which you define them in your form class. Forexample, in theContactForm 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 defaultForm.field_order=None, which retains the order in which youdefine the fields in your form class. Iffield_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 ittoNone without having to redefine ordering.
You can also use theForm.field_order argument to aForm tooverride the field order. If aForm definesfield_orderand you includefield_order when instantiatingtheForm, then the latterfield_order will have precedence.
- Form.order_fields(field_order)¶
You may rearrange the fields any time usingorder_fields() with a list offield names as infield_order.
How errors are displayed¶
If you render a boundForm 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<ulclass="errorlist"> near thefield. The particular positioning of the error messages depends on the outputmethod you’re using:
>>>data={..."subject":"",..."message":"Hi there",..."sender":"invalid email address",..."cc_myself":True,...}>>>f=ContactForm(data,auto_id=False)>>>print(f)<div>Subject: <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="subject" maxlength="100" required aria-invalid="true"></div><div>Message: <textarea name="message" cols="40" rows="10" required>Hi there</textarea></div><div>Sender: <ul class="errorlist"><li>Enter a valid email address.</li></ul> <input type="email" name="sender" value="invalid email address" required aria-invalid="true"></div><div>Cc myself: <input type="checkbox" name="cc_myself" checked></div>
Customizing the error list format¶
- classErrorList(initlist=None,error_class=None,renderer=None)¶
By default, forms use
django.forms.utils.ErrorListto format validationerrors.ErrorListis a list like object whereinitlistis thelist of errors. In addition this class has the following attributes andmethods.- error_class¶
The CSS classes to be used when rendering the error list. Any providedclasses are added to the default
errorlistclass.
- renderer¶
Specifies therenderer to use for
ErrorList.Defaults toNonewhich means to use the default rendererspecified by theFORM_RENDERERsetting.
- template_name¶
The name of the template used when calling
__str__orrender(). By default this is'django/forms/errors/list/default.html'which is a proxy for the'ul.html'template.
- template_name_text¶
The name of the template used when calling
as_text(). By defaultthis is'django/forms/errors/list/text.html'. This template rendersthe errors as a list of bullet points.
- template_name_ul¶
The name of the template used when calling
as_ul(). By defaultthis is'django/forms/errors/list/ul.html'. This template rendersthe errors in<li>tags with a wrapping<ul>with the CSSclasses as defined byerror_class.
- get_context()¶
Return context for rendering of errors in a template.
The available context is:
errors: A list of the errors.error_class: A string of CSS classes.
- render(template_name=None,context=None,renderer=None)¶
The render method is called by
__str__as well as by theas_ul()method.All arguments are optional and will default to:
template_name: Value returned bytemplate_namecontext: Value returned byget_context()renderer: Value returned byrenderer
- as_text()¶
Renders the error list using the template defined by
template_name_text.
- as_ul()¶
Renders the error list using the template defined by
template_name_ul.
If you’d like to customize the rendering of errors this can be achieved byoverriding the
template_nameattribute or more generally byoverriding the default template, see alsoOverriding built-in form templates.
More granular output¶
Theas_p(),as_ul(), andas_table() methods are shortcuts –they’re not the only way a form object can be displayed.
- classBoundField[source]¶
Used to display HTML or access attributes for a single field of a
Forminstance.The
__str__()method of this object displays the HTML for this field.
To retrieve a singleBoundField, use dictionary lookup syntax on your formusing the field’s name as the key:
>>>form=ContactForm()>>>print(form["subject"])<input id="id_subject" type="text" name="subject" maxlength="100" required>
To retrieve allBoundField objects, iterate the form:
>>>form=ContactForm()>>>forboundfieldinform:...print(boundfield)...<input id="id_subject" type="text" name="subject" maxlength="100" required><input type="text" name="message" id="id_message" required><input type="email" name="sender" id="id_sender" required><input type="checkbox" name="cc_myself" id="id_cc_myself">
The field-specific output honors the form object’sauto_id setting:
>>>f=ContactForm(auto_id=False)>>>print(f["message"])<input type="text" name="message" required>>>>f=ContactForm(auto_id="id_%s")>>>print(f["message"])<input type="text" name="message" id="id_message" required>
Attributes ofBoundField¶
- BoundField.auto_id¶
The HTML ID attribute for this
BoundField. Returns an empty stringifForm.auto_idisFalse.
- BoundField.data¶
This property returns the data for this
BoundFieldextracted by the widget’svalue_from_datadict()method, orNoneif it wasn’t given:>>>unbound_form=ContactForm()>>>print(unbound_form["subject"].data)None>>>bound_form=ContactForm(data={"subject":"My Subject"})>>>print(bound_form["subject"].data)My Subject
- BoundField.errors¶
Alist-like object that is displayedas an HTML
<ulclass="errorlist">when printed:>>>data={"subject":"hi","message":"","sender":"","cc_myself":""}>>>f=ContactForm(data,auto_id=False)>>>print(f["message"])<input type="text" name="message" required aria-invalid="true">>>>f["message"].errors['This field is required.']>>>print(f["message"].errors)<ul class="errorlist"><li>This field is required.</li></ul>>>>f["subject"].errors[]>>>print(f["subject"].errors)>>>str(f["subject"].errors)''
When rendering a field with errors,
aria-invalid="true"will be set onthe field’s widget to indicate there is an error to screen reader users.Changed in Django 5.0:The
aria-invalid="true"was added when a field has errors.
- BoundField.field¶
The form
Fieldinstance from the form class thatthisBoundFieldwraps.
- BoundField.form¶
The
Forminstance thisBoundFieldis bound to.
- BoundField.html_name¶
The name that will be used in the widget’s HTML
nameattribute. It takesthe formprefixinto 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()/legend_tag()will do thisfor you):<labelfor="{{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 settingattrson 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:
<labelfor="myFIELD">...</label><inputid="myFIELD"type="text"name="my_field"required>
- BoundField.initial¶
Use
BoundField.initialto retrieve initial data for a form field.It retrieves the data fromForm.initialif present, otherwisetryingField.initial. Callable values are evaluated. SeeInitial form values for more examples.BoundField.initialcaches its return value, which is usefulespecially when dealing with callables whose return values can change (e.g.datetime.noworuuid.uuid4):>>>fromdatetimeimportdatetime>>>classDatedCommentForm(CommentForm):...created=forms.DateTimeField(initial=datetime.now)...>>>f=DatedCommentForm()>>>f["created"].initialdatetime.datetime(2021, 7, 27, 9, 5, 54)>>>f["created"].initialdatetime.datetime(2021, 7, 27, 9, 5, 54)
Using
BoundField.initialis recommended overget_initial_for_field().
- BoundField.is_hidden¶
Returns
Trueif thisBoundField’s widget ishidden.
- BoundField.label¶
The
labelof the field. This is used inlabel_tag()/legend_tag().
- BoundField.name¶
The name of this field in the form:
>>>f=ContactForm()>>>print(f["subject"].name)subject>>>print(f["message"].name)message
- BoundField.template_name¶
- New in Django 5.0.
The name of the template rendered with
BoundField.as_field_group().A property returning the value of the
template_nameif set otherwisefield_template_name.
- BoundField.use_fieldset¶
Returns the value of this BoundField widget’s
use_fieldsetattribute.
- BoundField.widget_type¶
Returns the lowercased class name of the wrapped field’s widget, with anytrailing
inputorwidgetremoved. This may be used when buildingforms where the layout is dependent upon the widget type. For example:{%forfieldinform%}{%iffield.widget_type=='checkbox'%} # render one way{%else%} # render another way{%endif%}{%endfor%}
Methods ofBoundField¶
- BoundField.as_field_group()¶
- New in Django 5.0.
Renders the field using
BoundField.render()with default valueswhich renders theBoundField, including its label, help text and errorsusing the template’stemplate_nameif setotherwisefield_template_name
- BoundField.as_hidden(attrs=None,**kwargs)[source]¶
Returns a string of HTML for representing this as an
<inputtype="hidden">.**kwargsare passed toas_widget().This method is primarily used internally. You should use a widget instead.
- BoundField.as_widget(widget=None,attrs=None,only_initial=False)[source]¶
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_initialis used by Django internals and should not be setexplicitly.
- BoundField.css_classes(extra_classes=None)[source]¶
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 the
css_classesmethod:>>>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.get_context()[source]¶
- New in Django 5.0.
Return the template context for rendering the field. The available contextis
fieldbeing the instance of the bound field.
- BoundField.label_tag(contents=None,attrs=None,label_suffix=None,tag=None)[source]¶
Renders a label tag for the form field using the template specified by
Form.template_name_label.The available context is:
field: This instance of theBoundField.contents: By default a concatenated string ofBoundField.labelandForm.label_suffix(orField.label_suffix, if set). This can be overridden by thecontentsandlabel_suffixarguments.attrs: Adictcontainingfor,Form.required_css_class, andid.idis generated by thefield’s widgetattrsorBoundField.auto_id. Additionalattributes can be provided by theattrsargument.use_tag: A boolean which isTrueif the label has anid.IfFalsethe default template omits thetag.tag: An optional string to customize the tag, defaults tolabel.
Tip
In your template
fieldis the instance of theBoundField.Thereforefield.fieldaccessesBoundField.fieldbeingthe field you declare, e.g.forms.CharField.To separately render the label tag of a form field, you can call its
label_tag()method:>>>f=ContactForm(data={"message":""})>>>print(f["message"].label_tag())<label for="id_message">Message:</label>
If you’d like to customize the rendering this can be achieved by overridingthe
Form.template_name_labelattribute or more generally byoverriding the default template, see alsoOverriding built-in form templates.
- BoundField.legend_tag(contents=None,attrs=None,label_suffix=None)[source]¶
Calls
label_tag()withtag='legend'to render the label with<legend>tags. This is useful when rendering radio and multiplecheckbox widgets where<legend>may be more appropriate than a<label>.
- BoundField.render(template_name=None,context=None,renderer=None)¶
- New in Django 5.0.
The render method is called by
as_field_group. All arguments areoptional and default to:template_name:BoundField.template_namecontext: Value returned byBoundField.get_context()renderer: Value returned byForm.default_renderer
By passing
template_nameyou can customize the template used for just asingle call.
- BoundField.value()[source]¶
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
CustomizingBoundField¶
If you need to access some additional information about a form field in atemplate and using a subclass ofField isn’tsufficient, consider also customizingBoundField.
A custom form field can overrideget_bound_field():
- Field.get_bound_field(form,field_name)[source]¶
Takes an instance of
Formand 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 aGPSCoordinatesField, for example, and want to be able toaccess additional information about the coordinates in a template, this couldbe implemented as follows:
classGPSCoordinatesBoundField(BoundField):@propertydefcountry(self):""" Return the country the coordinates lie in or None if it can't be determined. """value=self.value()ifvalue:returnget_country_from_coordinates(value)else:returnNoneclassGPSCoordinatesField(Field):defget_bound_field(self,form,field_name):returnGPSCoordinatesBoundField(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 haveFileField andImageField 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 theenctype as"multipart/form-data":
<formenctype="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 aFileField andImageField, you will need to specifya second argument when you bind your form. So if we extend ourContactForm to include anImageField calledmugshot, weneed to bind the file data containing the mugshot image:
# Bound form with an image field>>>fromdjango.core.files.uploadedfileimportSimpleUploadedFile>>>data={..."subject":"hello",..."message":"Hi there",..."sender":"foo@example.com",..."cc_myself":True,...}>>>file_data={"mugshot":SimpleUploadedFile("face.jpg",b"file data")}>>>f=ContactFormWithMugshot(data,file_data)
In practice, you will usually specifyrequest.FILES as the sourceof file data (just like you userequest.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 dataandfile 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. Theis_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:
{%ifform.is_multipart%}<formenctype="multipart/form-data"method="post"action="/foo/">{%else%}<formmethod="post"action="/foo/">{%endif%}{{form}}</form>
Subclassing forms¶
If you have multipleForm classes that share fields, you can usesubclassing to remove redundancy.
When you subclass a customForm 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. TheContactFormfields are ordered first:
>>>classContactFormWithPriority(ContactForm):...priority=forms.CharField()...>>>f=ContactFormWithPriority(auto_id=False)>>>print(f)<div>Subject:<input type="text" name="subject" maxlength="100" required></div><div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div><div>Sender:<input type="email" name="sender" required></div><div>Cc myself:<input type="checkbox" name="cc_myself"></div><div>Priority:<input type="text" name="priority" required></div>
It’s possible to subclass multiple forms, treating forms as mixins. In thisexample,BeatleForm subclasses bothPersonForm andInstrumentForm(in that order), and its field list includes the fields from the parentclasses:
>>>fromdjangoimportforms>>>classPersonForm(forms.Form):...first_name=forms.CharField()...last_name=forms.CharField()...>>>classInstrumentForm(forms.Form):...instrument=forms.CharField()...>>>classBeatleForm(InstrumentForm,PersonForm):...haircut_type=forms.CharField()...>>>b=BeatleForm(auto_id=False)>>>print(b)<div>First name:<input type="text" name="first_name" required></div><div>Last name:<input type="text" name="last_name" required></div><div>Instrument:<input type="text" name="instrument" required></div><div>Haircut type:<input type="text" name="haircut_type" required></div>
It’s possible to declaratively remove aField inherited from a parent classby setting the name of the field toNone on the subclass. For example:
>>>fromdjangoimportforms>>>classParentForm(forms.Form):...name=forms.CharField()...age=forms.IntegerField()...>>>classChildForm(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 theprefix keyword argument:
>>>mother=PersonForm(prefix="mother")>>>father=PersonForm(prefix="father")>>>print(mother)<div><label for="id_mother-first_name">First name:</label><input type="text" name="mother-first_name" required id="id_mother-first_name"></div><div><label for="id_mother-last_name">Last name:</label><input type="text" name="mother-last_name" required id="id_mother-last_name"></div>>>>print(father)<div><label for="id_father-first_name">First name:</label><input type="text" name="father-first_name" required id="id_father-first_name"></div><div><label for="id_father-last_name">Last name:</label><input type="text" name="father-last_name" required id="id_father-last_name"></div>
The prefix can also be specified on the form class:
>>>classPersonForm(forms.Form):.........prefix="person"...

