api.txt 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. =============
  2. The Forms API
  3. =============
  4. .. module:: django.forms
  5. .. admonition:: About this document
  6. This document covers the gritty details of Django's forms API. You should
  7. read the :doc:`introduction to working with forms </topics/forms/index>`
  8. first.
  9. .. _ref-forms-api-bound-unbound:
  10. Bound and unbound forms
  11. -----------------------
  12. A :class:`Form` instance is either **bound** to a set of data, or **unbound**.
  13. * If it's **bound** to a set of data, it's capable of validating that data
  14. and rendering the form as HTML with the data displayed in the HTML.
  15. * If it's **unbound**, it cannot do validation (because there's no data to
  16. validate!), but it can still render the blank form as HTML.
  17. .. class:: Form
  18. To create an unbound :class:`Form` instance, simply instantiate the class::
  19. >>> f = ContactForm()
  20. To bind data to a form, pass the data as a dictionary as the first parameter to
  21. your :class:`Form` class constructor::
  22. >>> data = {'subject': 'hello',
  23. ... 'message': 'Hi there',
  24. ... 'sender': 'foo@example.com',
  25. ... 'cc_myself': True}
  26. >>> f = ContactForm(data)
  27. In this dictionary, the keys are the field names, which correspond to the
  28. attributes in your :class:`Form` class. The values are the data you're trying to
  29. validate. These will usually be strings, but there's no requirement that they be
  30. strings; the type of data you pass depends on the :class:`Field`, as we'll see
  31. in a moment.
  32. .. attribute:: Form.is_bound
  33. If you need to distinguish between bound and unbound form instances at runtime,
  34. check the value of the form's :attr:`~Form.is_bound` attribute::
  35. >>> f = ContactForm()
  36. >>> f.is_bound
  37. False
  38. >>> f = ContactForm({'subject': 'hello'})
  39. >>> f.is_bound
  40. True
  41. Note that passing an empty dictionary creates a *bound* form with empty data::
  42. >>> f = ContactForm({})
  43. >>> f.is_bound
  44. True
  45. If you have a bound :class:`Form` instance and want to change the data somehow,
  46. or if you want to bind an unbound :class:`Form` instance to some data, create
  47. another :class:`Form` instance. There is no way to change data in a
  48. :class:`Form` instance. Once a :class:`Form` instance has been created, you
  49. should consider its data immutable, whether it has data or not.
  50. Using forms to validate data
  51. ----------------------------
  52. .. method:: Form.is_valid()
  53. The primary task of a :class:`Form` object is to validate data. With a bound
  54. :class:`Form` instance, call the :meth:`~Form.is_valid` method to run validation
  55. and return a boolean designating whether the data was valid::
  56. >>> data = {'subject': 'hello',
  57. ... 'message': 'Hi there',
  58. ... 'sender': 'foo@example.com',
  59. ... 'cc_myself': True}
  60. >>> f = ContactForm(data)
  61. >>> f.is_valid()
  62. True
  63. Let's try with some invalid data. In this case, ``subject`` is blank (an error,
  64. because all fields are required by default) and ``sender`` is not a valid
  65. email address::
  66. >>> data = {'subject': '',
  67. ... 'message': 'Hi there',
  68. ... 'sender': 'invalid email address',
  69. ... 'cc_myself': True}
  70. >>> f = ContactForm(data)
  71. >>> f.is_valid()
  72. False
  73. .. attribute:: Form.errors
  74. Access the :attr:`~Form.errors` attribute to get a dictionary of error
  75. messages::
  76. >>> f.errors
  77. {'sender': [u'Enter a valid email address.'], 'subject': [u'This field is required.']}
  78. In this dictionary, the keys are the field names, and the values are lists of
  79. Unicode strings representing the error messages. The error messages are stored
  80. in lists because a field can have multiple error messages.
  81. You can access :attr:`~Form.errors` without having to call
  82. :meth:`~Form.is_valid` first. The form's data will be validated the first time
  83. either you call :meth:`~Form.is_valid` or access :attr:`~Form.errors`.
  84. The validation routines will only get called once, regardless of how many times
  85. you access :attr:`~Form.errors` or call :meth:`~Form.is_valid`. This means that
  86. if validation has side effects, those side effects will only be triggered once.
  87. .. method:: Form.errors.as_data()
  88. .. versionadded:: 1.7
  89. Returns a ``dict`` that maps fields to their original ``ValidationError``
  90. instances.
  91. >>> f.errors.as_data()
  92. {'sender': [ValidationError(['Enter a valid email address.'])],
  93. 'subject': [ValidationError(['This field is required.'])]}
  94. Use this method anytime you need to identify an error by its ``code``. This
  95. enables things like rewriting the error's message or writing custom logic in a
  96. view when a given error is present. It can also be used to serialize the errors
  97. in a custom format (e.g. XML); for instance, :meth:`~Form.errors.as_json()`
  98. relies on ``as_data()``.
  99. The need for the ``as_data()`` method is due to backwards compatibility.
  100. Previously ``ValidationError`` instances were lost as soon as their
  101. **rendered** error messages were added to the ``Form.errors`` dictionary.
  102. Ideally ``Form.errors`` would have stored ``ValidationError`` instances
  103. and methods with an ``as_`` prefix could render them, but it had to be done
  104. the other way around in order not to break code that expects rendered error
  105. messages in ``Form.errors``.
  106. .. method:: Form.errors.as_json()
  107. .. versionadded:: 1.7
  108. Returns the errors serialized as JSON.
  109. >>> f.errors.as_json()
  110. {"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
  111. "subject": [{"message": "This field is required.", "code": "required"}]}
  112. .. method:: Form.add_error(field, error)
  113. .. versionadded:: 1.7
  114. This method allows adding errors to specific fields from within the
  115. ``Form.clean()`` method, or from outside the form altogether; for instance
  116. from a view.
  117. The ``field`` argument is the name of the field to which the errors
  118. should be added. If its value is ``None`` the error will be treated as
  119. a non-field error as returned by ``Form.non_field_errors()``.
  120. The ``error`` argument can be a simple string, or preferably an instance of
  121. ``ValidationError``. See :ref:`raising-validation-error` for best practices
  122. when defining form errors.
  123. Note that ``Form.add_error()`` automatically removes the relevant field from
  124. ``cleaned_data``.
  125. Behavior of unbound forms
  126. ~~~~~~~~~~~~~~~~~~~~~~~~~
  127. It's meaningless to validate a form with no data, but, for the record, here's
  128. what happens with unbound forms::
  129. >>> f = ContactForm()
  130. >>> f.is_valid()
  131. False
  132. >>> f.errors
  133. {}
  134. Dynamic initial values
  135. ----------------------
  136. .. attribute:: Form.initial
  137. Use :attr:`~Form.initial` to declare the initial value of form fields at
  138. runtime. For example, you might want to fill in a ``username`` field with the
  139. username of the current session.
  140. To accomplish this, use the :attr:`~Form.initial` argument to a :class:`Form`.
  141. This argument, if given, should be a dictionary mapping field names to initial
  142. values. Only include the fields for which you're specifying an initial value;
  143. it's not necessary to include every field in your form. For example::
  144. >>> f = ContactForm(initial={'subject': 'Hi there!'})
  145. These values are only displayed for unbound forms, and they're not used as
  146. fallback values if a particular value isn't provided.
  147. Note that if a :class:`~django.forms.Field` defines :attr:`~Form.initial` *and*
  148. you include ``initial`` when instantiating the ``Form``, then the latter
  149. ``initial`` will have precedence. In this example, ``initial`` is provided both
  150. at the field level and at the form instance level, and the latter gets
  151. precedence::
  152. >>> from django import forms
  153. >>> class CommentForm(forms.Form):
  154. ... name = forms.CharField(initial='class')
  155. ... url = forms.URLField()
  156. ... comment = forms.CharField()
  157. >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
  158. >>> print(f)
  159. <tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr>
  160. <tr><th>Url:</th><td><input type="url" name="url" /></td></tr>
  161. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  162. Accessing the fields from the form
  163. ----------------------------------
  164. .. attribute:: Form.fields
  165. You can access the fields of :class:`Form` instance from its ``fields``
  166. attribute::
  167. >>> for row in f.fields.values(): print(row)
  168. ...
  169. <django.forms.fields.CharField object at 0x7ffaac632510>
  170. <django.forms.fields.URLField object at 0x7ffaac632f90>
  171. <django.forms.fields.CharField object at 0x7ffaac3aa050>
  172. >>> f.fields['name']
  173. <django.forms.fields.CharField object at 0x7ffaac6324d0>
  174. You can alter the field of :class:`Form` instance to change the way it is
  175. presented in the form::
  176. >>> f.as_table().split('\n')[0]
  177. '<tr><th>Name:</th><td><input name="name" type="text" value="instance" /></td></tr>'
  178. >>> f.fields['name'].label = "Username"
  179. >>> f.as_table().split('\n')[0]
  180. '<tr><th>Username:</th><td><input name="name" type="text" value="instance" /></td></tr>'
  181. Beware not to alter the ``base_fields`` attribute because this modification
  182. will influence all subsequent ``ContactForm`` instances within the same Python
  183. process::
  184. >>> f.base_fields['name'].label = "Username"
  185. >>> another_f = CommentForm(auto_id=False)
  186. >>> another_f.as_table().split('\n')[0]
  187. '<tr><th>Username:</th><td><input name="name" type="text" value="class" /></td></tr>'
  188. Accessing "clean" data
  189. ----------------------
  190. .. attribute:: Form.cleaned_data
  191. Each field in a :class:`Form` class is responsible not only for validating
  192. data, but also for "cleaning" it -- normalizing it to a consistent format. This
  193. is a nice feature, because it allows data for a particular field to be input in
  194. a variety of ways, always resulting in consistent output.
  195. For example, :class:`~django.forms.DateField` normalizes input into a
  196. Python ``datetime.date`` object. Regardless of whether you pass it a string in
  197. the format ``'1994-07-15'``, a ``datetime.date`` object, or a number of other
  198. formats, ``DateField`` will always normalize it to a ``datetime.date`` object
  199. as long as it's valid.
  200. Once you've created a :class:`~Form` instance with a set of data and validated
  201. it, you can access the clean data via its ``cleaned_data`` attribute::
  202. >>> data = {'subject': 'hello',
  203. ... 'message': 'Hi there',
  204. ... 'sender': 'foo@example.com',
  205. ... 'cc_myself': True}
  206. >>> f = ContactForm(data)
  207. >>> f.is_valid()
  208. True
  209. >>> f.cleaned_data
  210. {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
  211. Note that any text-based field -- such as ``CharField`` or ``EmailField`` --
  212. always cleans the input into a Unicode string. We'll cover the encoding
  213. implications later in this document.
  214. If your data does *not* validate, the ``cleaned_data`` dictionary contains
  215. only the valid fields::
  216. >>> data = {'subject': '',
  217. ... 'message': 'Hi there',
  218. ... 'sender': 'invalid email address',
  219. ... 'cc_myself': True}
  220. >>> f = ContactForm(data)
  221. >>> f.is_valid()
  222. False
  223. >>> f.cleaned_data
  224. {'cc_myself': True, 'message': u'Hi there'}
  225. ``cleaned_data`` will always *only* contain a key for fields defined in the
  226. ``Form``, even if you pass extra data when you define the ``Form``. In this
  227. example, we pass a bunch of extra fields to the ``ContactForm`` constructor,
  228. but ``cleaned_data`` contains only the form's fields::
  229. >>> data = {'subject': 'hello',
  230. ... 'message': 'Hi there',
  231. ... 'sender': 'foo@example.com',
  232. ... 'cc_myself': True,
  233. ... 'extra_field_1': 'foo',
  234. ... 'extra_field_2': 'bar',
  235. ... 'extra_field_3': 'baz'}
  236. >>> f = ContactForm(data)
  237. >>> f.is_valid()
  238. True
  239. >>> f.cleaned_data # Doesn't contain extra_field_1, etc.
  240. {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
  241. When the ``Form`` is valid, ``cleaned_data`` will include a key and value for
  242. *all* its fields, even if the data didn't include a value for some optional
  243. fields. In this example, the data dictionary doesn't include a value for the
  244. ``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::
  245. >>> from django.forms import Form
  246. >>> class OptionalPersonForm(Form):
  247. ... first_name = CharField()
  248. ... last_name = CharField()
  249. ... nick_name = CharField(required=False)
  250. >>> data = {'first_name': u'John', 'last_name': u'Lennon'}
  251. >>> f = OptionalPersonForm(data)
  252. >>> f.is_valid()
  253. True
  254. >>> f.cleaned_data
  255. {'nick_name': u'', 'first_name': u'John', 'last_name': u'Lennon'}
  256. In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an
  257. empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat
  258. empty values as an empty string. Each field type knows what its "blank" value
  259. is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For
  260. full details on each field's behavior in this case, see the "Empty value" note
  261. for each field in the "Built-in ``Field`` classes" section below.
  262. You can write code to perform validation for particular form fields (based on
  263. their name) or for the form as a whole (considering combinations of various
  264. fields). More information about this is in :doc:`/ref/forms/validation`.
  265. Outputting forms as HTML
  266. ------------------------
  267. The second task of a ``Form`` object is to render itself as HTML. To do so,
  268. simply ``print`` it::
  269. >>> f = ContactForm()
  270. >>> print(f)
  271. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
  272. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
  273. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>
  274. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
  275. If the form is bound to data, the HTML output will include that data
  276. appropriately. For example, if a field is represented by an
  277. ``<input type="text">``, the data will be in the ``value`` attribute. If a
  278. field is represented by an ``<input type="checkbox">``, then that HTML will
  279. include ``checked="checked"`` if appropriate::
  280. >>> data = {'subject': 'hello',
  281. ... 'message': 'Hi there',
  282. ... 'sender': 'foo@example.com',
  283. ... 'cc_myself': True}
  284. >>> f = ContactForm(data)
  285. >>> print(f)
  286. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" /></td></tr>
  287. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr>
  288. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" value="foo@example.com" /></td></tr>
  289. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" checked="checked" /></td></tr>
  290. This default output is a two-column HTML table, with a ``<tr>`` for each field.
  291. Notice the following:
  292. * For flexibility, the output does *not* include the ``<table>`` and
  293. ``</table>`` tags, nor does it include the ``<form>`` and ``</form>``
  294. tags or an ``<input type="submit">`` tag. It's your job to do that.
  295. * Each field type has a default HTML representation. ``CharField`` is
  296. represented by an ``<input type="text">`` and ``EmailField`` by an
  297. ``<input type="email">``.
  298. ``BooleanField`` is represented by an ``<input type="checkbox">``. Note
  299. these are merely sensible defaults; you can specify which HTML to use for
  300. a given field by using widgets, which we'll explain shortly.
  301. * The HTML ``name`` for each tag is taken directly from its attribute name
  302. in the ``ContactForm`` class.
  303. * The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and
  304. ``'Cc myself:'`` is generated from the field name by converting all
  305. underscores to spaces and upper-casing the first letter. Again, note
  306. these are merely sensible defaults; you can also specify labels manually.
  307. * Each text label is surrounded in an HTML ``<label>`` tag, which points
  308. to the appropriate form field via its ``id``. Its ``id``, in turn, is
  309. generated by prepending ``'id_'`` to the field name. The ``id``
  310. attributes and ``<label>`` tags are included in the output by default, to
  311. follow best practices, but you can change that behavior.
  312. Although ``<table>`` output is the default output style when you ``print`` a
  313. form, other output styles are available. Each style is available as a method on
  314. a form object, and each rendering method returns a Unicode object.
  315. ``as_p()``
  316. ~~~~~~~~~~
  317. .. method:: Form.as_p()
  318. ``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
  319. containing one field::
  320. >>> f = ContactForm()
  321. >>> f.as_p()
  322. u'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>'
  323. >>> print(f.as_p())
  324. <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
  325. <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
  326. <p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></p>
  327. <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
  328. ``as_ul()``
  329. ~~~~~~~~~~~
  330. .. method:: Form.as_ul()
  331. ``as_ul()`` renders the form as a series of ``<li>`` tags, with each
  332. ``<li>`` containing one field. It does *not* include the ``<ul>`` or
  333. ``</ul>``, so that you can specify any HTML attributes on the ``<ul>`` for
  334. flexibility::
  335. >>> f = ContactForm()
  336. >>> f.as_ul()
  337. u'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>'
  338. >>> print(f.as_ul())
  339. <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>
  340. <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
  341. <li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></li>
  342. <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>
  343. ``as_table()``
  344. ~~~~~~~~~~~~~~
  345. .. method:: Form.as_table()
  346. Finally, ``as_table()`` outputs the form as an HTML ``<table>``. This is
  347. exactly the same as ``print``. In fact, when you ``print`` a form object,
  348. it calls its ``as_table()`` method behind the scenes::
  349. >>> f = ContactForm()
  350. >>> f.as_table()
  351. u'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></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>'
  352. >>> print(f.as_table())
  353. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
  354. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
  355. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>
  356. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
  357. Styling required or erroneous form rows
  358. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  359. .. attribute:: Form.error_css_class
  360. .. attribute:: Form.required_css_class
  361. It's pretty common to style form rows and fields that are required or have
  362. errors. For example, you might want to present required form rows in bold and
  363. highlight errors in red.
  364. The :class:`Form` class has a couple of hooks you can use to add ``class``
  365. attributes to required rows or to rows with errors: simply set the
  366. :attr:`Form.error_css_class` and/or :attr:`Form.required_css_class`
  367. attributes::
  368. from django.forms import Form
  369. class ContactForm(Form):
  370. error_css_class = 'error'
  371. required_css_class = 'required'
  372. # ... and the rest of your fields here
  373. Once you've done that, rows will be given ``"error"`` and/or ``"required"``
  374. classes, as needed. The HTML will look something like::
  375. >>> f = ContactForm(data)
  376. >>> print(f.as_table())
  377. <tr class="required"><th><label for="id_subject">Subject:</label> ...
  378. <tr class="required"><th><label for="id_message">Message:</label> ...
  379. <tr class="required error"><th><label for="id_sender">Sender:</label> ...
  380. <tr><th><label for="id_cc_myself">Cc myself:<label> ...
  381. .. _ref-forms-api-configuring-label:
  382. Configuring form elements' HTML ``id`` attributes and ``<label>`` tags
  383. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  384. .. attribute:: Form.auto_id
  385. By default, the form rendering methods include:
  386. * HTML ``id`` attributes on the form elements.
  387. * The corresponding ``<label>`` tags around the labels. An HTML ``<label>`` tag
  388. designates which label text is associated with which form element. This small
  389. enhancement makes forms more usable and more accessible to assistive devices.
  390. It's always a good idea to use ``<label>`` tags.
  391. The ``id`` attribute values are generated by prepending ``id_`` to the form
  392. field names. This behavior is configurable, though, if you want to change the
  393. ``id`` convention or remove HTML ``id`` attributes and ``<label>`` tags
  394. entirely.
  395. Use the ``auto_id`` argument to the ``Form`` constructor to control the ``id``
  396. and label behavior. This argument must be ``True``, ``False`` or a string.
  397. If ``auto_id`` is ``False``, then the form output will not include ``<label>``
  398. tags nor ``id`` attributes::
  399. >>> f = ContactForm(auto_id=False)
  400. >>> print(f.as_table())
  401. <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></tr>
  402. <tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
  403. <tr><th>Sender:</th><td><input type="email" name="sender" /></td></tr>
  404. <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
  405. >>> print(f.as_ul())
  406. <li>Subject: <input type="text" name="subject" maxlength="100" /></li>
  407. <li>Message: <input type="text" name="message" /></li>
  408. <li>Sender: <input type="email" name="sender" /></li>
  409. <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
  410. >>> print(f.as_p())
  411. <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
  412. <p>Message: <input type="text" name="message" /></p>
  413. <p>Sender: <input type="email" name="sender" /></p>
  414. <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
  415. If ``auto_id`` is set to ``True``, then the form output *will* include
  416. ``<label>`` tags and will simply use the field name as its ``id`` for each form
  417. field::
  418. >>> f = ContactForm(auto_id=True)
  419. >>> print(f.as_table())
  420. <tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" /></td></tr>
  421. <tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" /></td></tr>
  422. <tr><th><label for="sender">Sender:</label></th><td><input type="email" name="sender" id="sender" /></td></tr>
  423. <tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr>
  424. >>> print(f.as_ul())
  425. <li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></li>
  426. <li><label for="message">Message:</label> <input type="text" name="message" id="message" /></li>
  427. <li><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" /></li>
  428. <li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li>
  429. >>> print(f.as_p())
  430. <p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></p>
  431. <p><label for="message">Message:</label> <input type="text" name="message" id="message" /></p>
  432. <p><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" /></p>
  433. <p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></p>
  434. If ``auto_id`` is set to a string containing the format character ``'%s'``,
  435. then the form output will include ``<label>`` tags, and will generate ``id``
  436. attributes based on the format string. For example, for a format string
  437. ``'field_%s'``, a field named ``subject`` will get the ``id`` value
  438. ``'field_subject'``. Continuing our example::
  439. >>> f = ContactForm(auto_id='id_for_%s')
  440. >>> print(f.as_table())
  441. <tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" /></td></tr>
  442. <tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" /></td></tr>
  443. <tr><th><label for="id_for_sender">Sender:</label></th><td><input type="email" name="sender" id="id_for_sender" /></td></tr>
  444. <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>
  445. >>> print(f.as_ul())
  446. <li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
  447. <li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></li>
  448. <li><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" /></li>
  449. <li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
  450. >>> print(f.as_p())
  451. <p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></p>
  452. <p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></p>
  453. <p><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" /></p>
  454. <p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></p>
  455. If ``auto_id`` is set to any other true value -- such as a string that doesn't
  456. include ``%s`` -- then the library will act as if ``auto_id`` is ``True``.
  457. By default, ``auto_id`` is set to the string ``'id_%s'``.
  458. .. attribute:: Form.label_suffix
  459. A translatable string (defaults to a colon (``:``) in English) that will be
  460. appended after any label name when a form is rendered.
  461. .. versionchanged:: 1.6
  462. The default ``label_suffix`` is translatable.
  463. It's possible to customize that character, or omit it entirely, using the
  464. ``label_suffix`` parameter::
  465. >>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
  466. >>> print(f.as_ul())
  467. <li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
  468. <li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" /></li>
  469. <li><label for="id_for_sender">Sender</label> <input type="email" name="sender" id="id_for_sender" /></li>
  470. <li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
  471. >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
  472. >>> print(f.as_ul())
  473. <li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
  474. <li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" /></li>
  475. <li><label for="id_for_sender">Sender -></label> <input type="email" name="sender" id="id_for_sender" /></li>
  476. <li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
  477. Note that the label suffix is added only if the last character of the
  478. label isn't a punctuation character (in English, those are ``.``, ``!``, ``?``
  479. or ``:``).
  480. .. versionadded:: 1.6
  481. You can also customize the ``label_suffix`` on a per-field basis using the
  482. ``label_suffix`` parameter to :meth:`~django.forms.BoundField.label_tag`.
  483. Notes on field ordering
  484. ~~~~~~~~~~~~~~~~~~~~~~~
  485. In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are
  486. displayed in the order in which you define them in your form class. For
  487. example, in the ``ContactForm`` example, the fields are defined in the order
  488. ``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML
  489. output, just change the order in which those fields are listed in the class.
  490. How errors are displayed
  491. ~~~~~~~~~~~~~~~~~~~~~~~~
  492. If you render a bound ``Form`` object, the act of rendering will automatically
  493. run the form's validation if it hasn't already happened, and the HTML output
  494. will include the validation errors as a ``<ul class="errorlist">`` near the
  495. field. The particular positioning of the error messages depends on the output
  496. method you're using::
  497. >>> data = {'subject': '',
  498. ... 'message': 'Hi there',
  499. ... 'sender': 'invalid email address',
  500. ... 'cc_myself': True}
  501. >>> f = ContactForm(data, auto_id=False)
  502. >>> print(f.as_table())
  503. <tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" /></td></tr>
  504. <tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></td></tr>
  505. <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" /></td></tr>
  506. <tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /></td></tr>
  507. >>> print(f.as_ul())
  508. <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" /></li>
  509. <li>Message: <input type="text" name="message" value="Hi there" /></li>
  510. <li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input type="email" name="sender" value="invalid email address" /></li>
  511. <li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li>
  512. >>> print(f.as_p())
  513. <p><ul class="errorlist"><li>This field is required.</li></ul></p>
  514. <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
  515. <p>Message: <input type="text" name="message" value="Hi there" /></p>
  516. <p><ul class="errorlist"><li>Enter a valid email address.</li></ul></p>
  517. <p>Sender: <input type="email" name="sender" value="invalid email address" /></p>
  518. <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
  519. Customizing the error list format
  520. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  521. By default, forms use ``django.forms.utils.ErrorList`` to format validation
  522. errors. If you'd like to use an alternate class for displaying errors, you can
  523. pass that in at construction time (replace ``__str__`` by ``__unicode__`` on
  524. Python 2)::
  525. >>> from django.forms.utils import ErrorList
  526. >>> class DivErrorList(ErrorList):
  527. ... def __str__(self): # __unicode__ on Python 2
  528. ... return self.as_divs()
  529. ... def as_divs(self):
  530. ... if not self: return ''
  531. ... return '<div class="errorlist">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self])
  532. >>> f = ContactForm(data, auto_id=False, error_class=DivErrorList)
  533. >>> f.as_p()
  534. <div class="errorlist"><div class="error">This field is required.</div></div>
  535. <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
  536. <p>Message: <input type="text" name="message" value="Hi there" /></p>
  537. <div class="errorlist"><div class="error">Enter a valid email address.</div></div>
  538. <p>Sender: <input type="email" name="sender" value="invalid email address" /></p>
  539. <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
  540. .. versionchanged:: 1.7
  541. ``django.forms.util`` was renamed to ``django.forms.utils``.
  542. More granular output
  543. ~~~~~~~~~~~~~~~~~~~~
  544. The ``as_p()``, ``as_ul()`` and ``as_table()`` methods are simply shortcuts for
  545. lazy developers -- they're not the only way a form object can be displayed.
  546. .. class:: BoundField
  547. Used to display HTML or access attributes for a single field of a
  548. :class:`Form` instance.
  549. The ``__str__()`` (``__unicode__`` on Python 2) method of this
  550. object displays the HTML for this field.
  551. To retrieve a single ``BoundField``, use dictionary lookup syntax on your form
  552. using the field's name as the key::
  553. >>> form = ContactForm()
  554. >>> print(form['subject'])
  555. <input id="id_subject" type="text" name="subject" maxlength="100" />
  556. To retrieve all ``BoundField`` objects, iterate the form::
  557. >>> form = ContactForm()
  558. >>> for boundfield in form: print(boundfield)
  559. <input id="id_subject" type="text" name="subject" maxlength="100" />
  560. <input type="text" name="message" id="id_message" />
  561. <input type="email" name="sender" id="id_sender" />
  562. <input type="checkbox" name="cc_myself" id="id_cc_myself" />
  563. The field-specific output honors the form object's ``auto_id`` setting::
  564. >>> f = ContactForm(auto_id=False)
  565. >>> print(f['message'])
  566. <input type="text" name="message" />
  567. >>> f = ContactForm(auto_id='id_%s')
  568. >>> print(f['message'])
  569. <input type="text" name="message" id="id_message" />
  570. For a field's list of errors, access the field's ``errors`` attribute.
  571. .. attribute:: BoundField.errors
  572. A list-like object that is displayed as an HTML ``<ul class="errorlist">``
  573. when printed::
  574. >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
  575. >>> f = ContactForm(data, auto_id=False)
  576. >>> print(f['message'])
  577. <input type="text" name="message" />
  578. >>> f['message'].errors
  579. [u'This field is required.']
  580. >>> print(f['message'].errors)
  581. <ul class="errorlist"><li>This field is required.</li></ul>
  582. >>> f['subject'].errors
  583. []
  584. >>> print(f['subject'].errors)
  585. >>> str(f['subject'].errors)
  586. ''
  587. .. method:: BoundField.label_tag(contents=None, attrs=None, label_suffix=None)
  588. To separately render the label tag of a form field, you can call its
  589. ``label_tag`` method::
  590. >>> f = ContactForm(data)
  591. >>> print(f['message'].label_tag())
  592. <label for="id_message">Message:</label>
  593. Optionally, you can provide the ``contents`` parameter which will replace the
  594. auto-generated label tag. An optional ``attrs`` dictionary may contain
  595. additional attributes for the ``<label>`` tag.
  596. .. versionchanged:: 1.6
  597. The label now includes the form's :attr:`~django.forms.Form.label_suffix`
  598. (a colon, by default).
  599. .. versionadded:: 1.6
  600. The optional ``label_suffix`` parameter allows you to override the form's
  601. :attr:`~django.forms.Form.label_suffix`. For example, you can use an empty
  602. string to hide the label on selected fields. If you need to do this in a
  603. template, you could write a custom filter to allow passing parameters to
  604. ``label_tag``.
  605. .. method:: BoundField.css_classes()
  606. When you use Django's rendering shortcuts, CSS classes are used to
  607. indicate required form fields or fields that contain errors. If you're
  608. manually rendering a form, you can access these CSS classes using the
  609. ``css_classes`` method::
  610. >>> f = ContactForm(data)
  611. >>> f['message'].css_classes()
  612. 'required'
  613. If you want to provide some additional classes in addition to the
  614. error and required classes that may be required, you can provide
  615. those classes as an argument::
  616. >>> f = ContactForm(data)
  617. >>> f['message'].css_classes('foo bar')
  618. 'foo bar required'
  619. .. method:: BoundField.value()
  620. Use this method to render the raw value of this field as it would be rendered
  621. by a ``Widget``::
  622. >>> initial = {'subject': 'welcome'}
  623. >>> unbound_form = ContactForm(initial=initial)
  624. >>> bound_form = ContactForm(data, initial=initial)
  625. >>> print(unbound_form['subject'].value())
  626. welcome
  627. >>> print(bound_form['subject'].value())
  628. hi
  629. .. attribute:: BoundField.id_for_label
  630. Use this property to render the ID of this field. For example, if you are
  631. manually constructing a ``<label>`` in your template (despite the fact that
  632. :meth:`~BoundField.label_tag` will do this for you):
  633. .. code-block:: html+django
  634. <label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }}
  635. By default, this will be the field's name prefixed by ``id_``
  636. ("``id_my_field``" for the example above). You may modify the ID by setting
  637. :attr:`~django.forms.Widget.attrs` on the field's widget. For example,
  638. declaring a field like this::
  639. my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'}))
  640. and using the template above, would render something like:
  641. .. code-block:: html
  642. <label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" />
  643. .. _binding-uploaded-files:
  644. Binding uploaded files to a form
  645. --------------------------------
  646. Dealing with forms that have ``FileField`` and ``ImageField`` fields
  647. is a little more complicated than a normal form.
  648. Firstly, in order to upload files, you'll need to make sure that your
  649. ``<form>`` element correctly defines the ``enctype`` as
  650. ``"multipart/form-data"``::
  651. <form enctype="multipart/form-data" method="post" action="/foo/">
  652. Secondly, when you use the form, you need to bind the file data. File
  653. data is handled separately to normal form data, so when your form
  654. contains a ``FileField`` and ``ImageField``, you will need to specify
  655. a second argument when you bind your form. So if we extend our
  656. ContactForm to include an ``ImageField`` called ``mugshot``, we
  657. need to bind the file data containing the mugshot image::
  658. # Bound form with an image field
  659. >>> from django.core.files.uploadedfile import SimpleUploadedFile
  660. >>> data = {'subject': 'hello',
  661. ... 'message': 'Hi there',
  662. ... 'sender': 'foo@example.com',
  663. ... 'cc_myself': True}
  664. >>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)}
  665. >>> f = ContactFormWithMugshot(data, file_data)
  666. In practice, you will usually specify ``request.FILES`` as the source
  667. of file data (just like you use ``request.POST`` as the source of
  668. form data)::
  669. # Bound form with an image field, data from the request
  670. >>> f = ContactFormWithMugshot(request.POST, request.FILES)
  671. Constructing an unbound form is the same as always -- just omit both
  672. form data *and* file data::
  673. # Unbound form with a image field
  674. >>> f = ContactFormWithMugshot()
  675. Testing for multipart forms
  676. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  677. .. method:: Form.is_multipart()
  678. If you're writing reusable views or templates, you may not know ahead of time
  679. whether your form is a multipart form or not. The ``is_multipart()`` method
  680. tells you whether the form requires multipart encoding for submission::
  681. >>> f = ContactFormWithMugshot()
  682. >>> f.is_multipart()
  683. True
  684. Here's an example of how you might use this in a template::
  685. {% if form.is_multipart %}
  686. <form enctype="multipart/form-data" method="post" action="/foo/">
  687. {% else %}
  688. <form method="post" action="/foo/">
  689. {% endif %}
  690. {{ form }}
  691. </form>
  692. Subclassing forms
  693. -----------------
  694. If you have multiple ``Form`` classes that share fields, you can use
  695. subclassing to remove redundancy.
  696. When you subclass a custom ``Form`` class, the resulting subclass will
  697. include all fields of the parent class(es), followed by the fields you define
  698. in the subclass.
  699. In this example, ``ContactFormWithPriority`` contains all the fields from
  700. ``ContactForm``, plus an additional field, ``priority``. The ``ContactForm``
  701. fields are ordered first::
  702. >>> class ContactFormWithPriority(ContactForm):
  703. ... priority = forms.CharField()
  704. >>> f = ContactFormWithPriority(auto_id=False)
  705. >>> print(f.as_ul())
  706. <li>Subject: <input type="text" name="subject" maxlength="100" /></li>
  707. <li>Message: <input type="text" name="message" /></li>
  708. <li>Sender: <input type="email" name="sender" /></li>
  709. <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
  710. <li>Priority: <input type="text" name="priority" /></li>
  711. It's possible to subclass multiple forms, treating forms as "mix-ins." In this
  712. example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``
  713. (in that order), and its field list includes the fields from the parent
  714. classes::
  715. >>> from django.forms import Form
  716. >>> class PersonForm(Form):
  717. ... first_name = CharField()
  718. ... last_name = CharField()
  719. >>> class InstrumentForm(Form):
  720. ... instrument = CharField()
  721. >>> class BeatleForm(PersonForm, InstrumentForm):
  722. ... haircut_type = CharField()
  723. >>> b = BeatleForm(auto_id=False)
  724. >>> print(b.as_ul())
  725. <li>First name: <input type="text" name="first_name" /></li>
  726. <li>Last name: <input type="text" name="last_name" /></li>
  727. <li>Instrument: <input type="text" name="instrument" /></li>
  728. <li>Haircut type: <input type="text" name="haircut_type" /></li>
  729. .. versionadded:: 1.7
  730. * It's possible to opt-out from a ``Field`` inherited from a parent class by
  731. shadowing it. While any non-``Field`` value works for this purpose, it's
  732. recommended to use ``None`` to make it explicit that a field is being
  733. nullified.
  734. .. _form-prefix:
  735. Prefixes for forms
  736. ------------------
  737. .. attribute:: Form.prefix
  738. You can put several Django forms inside one ``<form>`` tag. To give each
  739. ``Form`` its own namespace, use the ``prefix`` keyword argument::
  740. >>> mother = PersonForm(prefix="mother")
  741. >>> father = PersonForm(prefix="father")
  742. >>> print(mother.as_ul())
  743. <li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li>
  744. <li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li>
  745. >>> print(father.as_ul())
  746. <li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li>
  747. <li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li>