api.txt 37 KB

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