api.txt 40 KB

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