api.txt 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  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.clean()
  53. Implement a ``clean()`` method on your ``Form`` when you must add custom
  54. validation for fields that are interdependent. See
  55. :ref:`validating-fields-with-clean` for example usage.
  56. .. method:: Form.is_valid()
  57. The primary task of a :class:`Form` object is to validate data. With a bound
  58. :class:`Form` instance, call the :meth:`~Form.is_valid` method to run validation
  59. and return a boolean designating whether the data was valid::
  60. >>> data = {'subject': 'hello',
  61. ... 'message': 'Hi there',
  62. ... 'sender': 'foo@example.com',
  63. ... 'cc_myself': True}
  64. >>> f = ContactForm(data)
  65. >>> f.is_valid()
  66. True
  67. Let's try with some invalid data. In this case, ``subject`` is blank (an error,
  68. because all fields are required by default) and ``sender`` is not a valid
  69. email address::
  70. >>> data = {'subject': '',
  71. ... 'message': 'Hi there',
  72. ... 'sender': 'invalid email address',
  73. ... 'cc_myself': True}
  74. >>> f = ContactForm(data)
  75. >>> f.is_valid()
  76. False
  77. .. attribute:: Form.errors
  78. Access the :attr:`~Form.errors` attribute to get a dictionary of error
  79. messages::
  80. >>> f.errors
  81. {'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}
  82. In this dictionary, the keys are the field names, and the values are lists of
  83. Unicode strings representing the error messages. The error messages are stored
  84. in lists because a field can have multiple error messages.
  85. You can access :attr:`~Form.errors` without having to call
  86. :meth:`~Form.is_valid` first. The form's data will be validated the first time
  87. either you call :meth:`~Form.is_valid` or access :attr:`~Form.errors`.
  88. The validation routines will only get called once, regardless of how many times
  89. you access :attr:`~Form.errors` or call :meth:`~Form.is_valid`. This means that
  90. if validation has side effects, those side effects will only be triggered once.
  91. .. method:: Form.errors.as_data()
  92. Returns a ``dict`` that maps fields to their original ``ValidationError``
  93. instances.
  94. >>> f.errors.as_data()
  95. {'sender': [ValidationError(['Enter a valid email address.'])],
  96. 'subject': [ValidationError(['This field is required.'])]}
  97. Use this method anytime you need to identify an error by its ``code``. This
  98. enables things like rewriting the error's message or writing custom logic in a
  99. view when a given error is present. It can also be used to serialize the errors
  100. in a custom format (e.g. XML); for instance, :meth:`~Form.errors.as_json()`
  101. relies on ``as_data()``.
  102. The need for the ``as_data()`` method is due to backwards compatibility.
  103. Previously ``ValidationError`` instances were lost as soon as their
  104. **rendered** error messages were added to the ``Form.errors`` dictionary.
  105. Ideally ``Form.errors`` would have stored ``ValidationError`` instances
  106. and methods with an ``as_`` prefix could render them, but it had to be done
  107. the other way around in order not to break code that expects rendered error
  108. messages in ``Form.errors``.
  109. .. method:: Form.errors.as_json(escape_html=False)
  110. Returns the errors serialized as JSON.
  111. >>> f.errors.as_json()
  112. {"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
  113. "subject": [{"message": "This field is required.", "code": "required"}]}
  114. By default, ``as_json()`` does not escape its output. If you are using it for
  115. something like AJAX requests to a form view where the client interprets the
  116. response and inserts errors into the page, you'll want to be sure to escape the
  117. results on the client-side to avoid the possibility of a cross-site scripting
  118. attack. It's trivial to do so using a JavaScript library like jQuery - simply
  119. use ``$(el).text(errorText)`` rather than ``.html()``.
  120. If for some reason you don't want to use client-side escaping, you can also
  121. set ``escape_html=True`` and error messages will be escaped so you can use them
  122. directly in HTML.
  123. .. method:: Form.add_error(field, error)
  124. This method allows adding errors to specific fields from within the
  125. ``Form.clean()`` method, or from outside the form altogether; for instance
  126. from a view.
  127. The ``field`` argument is the name of the field to which the errors
  128. should be added. If its value is ``None`` the error will be treated as
  129. a non-field error as returned by :meth:`Form.non_field_errors()
  130. <django.forms.Form.non_field_errors>`.
  131. The ``error`` argument can be a simple string, or preferably an instance of
  132. ``ValidationError``. See :ref:`raising-validation-error` for best practices
  133. when defining form errors.
  134. Note that ``Form.add_error()`` automatically removes the relevant field from
  135. ``cleaned_data``.
  136. .. method:: Form.has_error(field, code=None)
  137. This method returns a boolean designating whether a field has an error with
  138. a specific error ``code``. If ``code`` is ``None``, it will return ``True``
  139. if the field contains any errors at all.
  140. To check for non-field errors use
  141. :data:`~django.core.exceptions.NON_FIELD_ERRORS` as the ``field`` parameter.
  142. .. method:: Form.non_field_errors()
  143. This method returns the list of errors from :attr:`Form.errors
  144. <django.forms.Form.errors>` that aren't associated with a particular field.
  145. This includes ``ValidationError``\s that are raised in :meth:`Form.clean()
  146. <django.forms.Form.clean>` and errors added using :meth:`Form.add_error(None,
  147. "...") <django.forms.Form.add_error>`.
  148. Behavior of unbound forms
  149. -------------------------
  150. It's meaningless to validate a form with no data, but, for the record, here's
  151. what happens with unbound forms::
  152. >>> f = ContactForm()
  153. >>> f.is_valid()
  154. False
  155. >>> f.errors
  156. {}
  157. Dynamic initial values
  158. ======================
  159. .. attribute:: Form.initial
  160. Use :attr:`~Form.initial` to declare the initial value of form fields at
  161. runtime. For example, you might want to fill in a ``username`` field with the
  162. username of the current session.
  163. To accomplish this, use the :attr:`~Form.initial` argument to a :class:`Form`.
  164. This argument, if given, should be a dictionary mapping field names to initial
  165. values. Only include the fields for which you're specifying an initial value;
  166. it's not necessary to include every field in your form. For example::
  167. >>> f = ContactForm(initial={'subject': 'Hi there!'})
  168. These values are only displayed for unbound forms, and they're not used as
  169. fallback values if a particular value isn't provided.
  170. Note that if a :class:`~django.forms.Field` defines :attr:`~Form.initial` *and*
  171. you include ``initial`` when instantiating the ``Form``, then the latter
  172. ``initial`` will have precedence. In this example, ``initial`` is provided both
  173. at the field level and at the form instance level, and the latter gets
  174. precedence::
  175. >>> from django import forms
  176. >>> class CommentForm(forms.Form):
  177. ... name = forms.CharField(initial='class')
  178. ... url = forms.URLField()
  179. ... comment = forms.CharField()
  180. >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
  181. >>> print(f)
  182. <tr><th>Name:</th><td><input type="text" name="name" value="instance" required /></td></tr>
  183. <tr><th>Url:</th><td><input type="url" name="url" required /></td></tr>
  184. <tr><th>Comment:</th><td><input type="text" name="comment" required /></td></tr>
  185. Checking which form data has changed
  186. ====================================
  187. .. method:: Form.has_changed()
  188. Use the ``has_changed()`` method on your ``Form`` when you need to check if the
  189. form data has been changed from the initial data.
  190. >>> data = {'subject': 'hello',
  191. ... 'message': 'Hi there',
  192. ... 'sender': 'foo@example.com',
  193. ... 'cc_myself': True}
  194. >>> f = ContactForm(data, initial=data)
  195. >>> f.has_changed()
  196. False
  197. When the form is submitted, we reconstruct it and provide the original data
  198. so that the comparison can be done:
  199. >>> f = ContactForm(request.POST, initial=data)
  200. >>> f.has_changed()
  201. ``has_changed()`` will be ``True`` if the data from ``request.POST`` differs
  202. from what was provided in :attr:`~Form.initial` or ``False`` otherwise. The
  203. result is computed by calling :meth:`Field.has_changed` for each field in the
  204. form.
  205. .. attribute:: Form.changed_data
  206. The ``changed_data`` attribute returns a list of the names of the fields whose
  207. values in the form's bound data (usually ``request.POST``) differ from what was
  208. provided in :attr:`~Form.initial`. It returns an empty list if no data differs.
  209. >>> f = ContactForm(request.POST, initial=data)
  210. >>> if f.has_changed():
  211. ... print("The following fields changed: %s" % ", ".join(f.changed_data))
  212. Accessing the fields from the form
  213. ==================================
  214. .. attribute:: Form.fields
  215. You can access the fields of :class:`Form` instance from its ``fields``
  216. attribute::
  217. >>> for row in f.fields.values(): print(row)
  218. ...
  219. <django.forms.fields.CharField object at 0x7ffaac632510>
  220. <django.forms.fields.URLField object at 0x7ffaac632f90>
  221. <django.forms.fields.CharField object at 0x7ffaac3aa050>
  222. >>> f.fields['name']
  223. <django.forms.fields.CharField object at 0x7ffaac6324d0>
  224. You can alter the field of :class:`Form` instance to change the way it is
  225. presented in the form::
  226. >>> f.as_table().split('\n')[0]
  227. '<tr><th>Name:</th><td><input name="name" type="text" value="instance" required /></td></tr>'
  228. >>> f.fields['name'].label = "Username"
  229. >>> f.as_table().split('\n')[0]
  230. '<tr><th>Username:</th><td><input name="name" type="text" value="instance" required /></td></tr>'
  231. Beware not to alter the ``base_fields`` attribute because this modification
  232. will influence all subsequent ``ContactForm`` instances within the same Python
  233. process::
  234. >>> f.base_fields['name'].label = "Username"
  235. >>> another_f = CommentForm(auto_id=False)
  236. >>> another_f.as_table().split('\n')[0]
  237. '<tr><th>Username:</th><td><input name="name" type="text" value="class" required /></td></tr>'
  238. Accessing "clean" data
  239. ======================
  240. .. attribute:: Form.cleaned_data
  241. Each field in a :class:`Form` class is responsible not only for validating
  242. data, but also for "cleaning" it -- normalizing it to a consistent format. This
  243. is a nice feature, because it allows data for a particular field to be input in
  244. a variety of ways, always resulting in consistent output.
  245. For example, :class:`~django.forms.DateField` normalizes input into a
  246. Python ``datetime.date`` object. Regardless of whether you pass it a string in
  247. the format ``'1994-07-15'``, a ``datetime.date`` object, or a number of other
  248. formats, ``DateField`` will always normalize it to a ``datetime.date`` object
  249. as long as it's valid.
  250. Once you've created a :class:`~Form` instance with a set of data and validated
  251. it, you can access the clean data via its ``cleaned_data`` attribute::
  252. >>> data = {'subject': 'hello',
  253. ... 'message': 'Hi there',
  254. ... 'sender': 'foo@example.com',
  255. ... 'cc_myself': True}
  256. >>> f = ContactForm(data)
  257. >>> f.is_valid()
  258. True
  259. >>> f.cleaned_data
  260. {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
  261. Note that any text-based field -- such as ``CharField`` or ``EmailField`` --
  262. always cleans the input into a Unicode string. We'll cover the encoding
  263. implications later in this document.
  264. If your data does *not* validate, the ``cleaned_data`` dictionary contains
  265. only the valid fields::
  266. >>> data = {'subject': '',
  267. ... 'message': 'Hi there',
  268. ... 'sender': 'invalid email address',
  269. ... 'cc_myself': True}
  270. >>> f = ContactForm(data)
  271. >>> f.is_valid()
  272. False
  273. >>> f.cleaned_data
  274. {'cc_myself': True, 'message': 'Hi there'}
  275. ``cleaned_data`` will always *only* contain a key for fields defined in the
  276. ``Form``, even if you pass extra data when you define the ``Form``. In this
  277. example, we pass a bunch of extra fields to the ``ContactForm`` constructor,
  278. but ``cleaned_data`` contains only the form's fields::
  279. >>> data = {'subject': 'hello',
  280. ... 'message': 'Hi there',
  281. ... 'sender': 'foo@example.com',
  282. ... 'cc_myself': True,
  283. ... 'extra_field_1': 'foo',
  284. ... 'extra_field_2': 'bar',
  285. ... 'extra_field_3': 'baz'}
  286. >>> f = ContactForm(data)
  287. >>> f.is_valid()
  288. True
  289. >>> f.cleaned_data # Doesn't contain extra_field_1, etc.
  290. {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
  291. When the ``Form`` is valid, ``cleaned_data`` will include a key and value for
  292. *all* its fields, even if the data didn't include a value for some optional
  293. fields. In this example, the data dictionary doesn't include a value for the
  294. ``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::
  295. >>> from django.forms import Form
  296. >>> class OptionalPersonForm(Form):
  297. ... first_name = CharField()
  298. ... last_name = CharField()
  299. ... nick_name = CharField(required=False)
  300. >>> data = {'first_name': 'John', 'last_name': 'Lennon'}
  301. >>> f = OptionalPersonForm(data)
  302. >>> f.is_valid()
  303. True
  304. >>> f.cleaned_data
  305. {'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}
  306. In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an
  307. empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat
  308. empty values as an empty string. Each field type knows what its "blank" value
  309. is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For
  310. full details on each field's behavior in this case, see the "Empty value" note
  311. for each field in the "Built-in ``Field`` classes" section below.
  312. You can write code to perform validation for particular form fields (based on
  313. their name) or for the form as a whole (considering combinations of various
  314. fields). More information about this is in :doc:`/ref/forms/validation`.
  315. .. _ref-forms-api-outputting-html:
  316. Outputting forms as HTML
  317. ========================
  318. The second task of a ``Form`` object is to render itself as HTML. To do so,
  319. simply ``print`` it::
  320. >>> f = ContactForm()
  321. >>> print(f)
  322. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required /></td></tr>
  323. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required /></td></tr>
  324. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required /></td></tr>
  325. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
  326. If the form is bound to data, the HTML output will include that data
  327. appropriately. For example, if a field is represented by an
  328. ``<input type="text">``, the data will be in the ``value`` attribute. If a
  329. field is represented by an ``<input type="checkbox">``, then that HTML will
  330. include ``checked="checked"`` if appropriate::
  331. >>> data = {'subject': 'hello',
  332. ... 'message': 'Hi there',
  333. ... 'sender': 'foo@example.com',
  334. ... 'cc_myself': True}
  335. >>> f = ContactForm(data)
  336. >>> print(f)
  337. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" required /></td></tr>
  338. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" required /></td></tr>
  339. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" value="foo@example.com" required /></td></tr>
  340. <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>
  341. This default output is a two-column HTML table, with a ``<tr>`` for each field.
  342. Notice the following:
  343. * For flexibility, the output does *not* include the ``<table>`` and
  344. ``</table>`` tags, nor does it include the ``<form>`` and ``</form>``
  345. tags or an ``<input type="submit">`` tag. It's your job to do that.
  346. * Each field type has a default HTML representation. ``CharField`` is
  347. represented by an ``<input type="text">`` and ``EmailField`` by an
  348. ``<input type="email">``.
  349. ``BooleanField`` is represented by an ``<input type="checkbox">``. Note
  350. these are merely sensible defaults; you can specify which HTML to use for
  351. a given field by using widgets, which we'll explain shortly.
  352. * The HTML ``name`` for each tag is taken directly from its attribute name
  353. in the ``ContactForm`` class.
  354. * The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and
  355. ``'Cc myself:'`` is generated from the field name by converting all
  356. underscores to spaces and upper-casing the first letter. Again, note
  357. these are merely sensible defaults; you can also specify labels manually.
  358. * Each text label is surrounded in an HTML ``<label>`` tag, which points
  359. to the appropriate form field via its ``id``. Its ``id``, in turn, is
  360. generated by prepending ``'id_'`` to the field name. The ``id``
  361. attributes and ``<label>`` tags are included in the output by default, to
  362. follow best practices, but you can change that behavior.
  363. Although ``<table>`` output is the default output style when you ``print`` a
  364. form, other output styles are available. Each style is available as a method on
  365. a form object, and each rendering method returns a Unicode object.
  366. ``as_p()``
  367. ----------
  368. .. method:: Form.as_p()
  369. ``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
  370. containing one field::
  371. >>> f = ContactForm()
  372. >>> f.as_p()
  373. '<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" required /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>'
  374. >>> print(f.as_p())
  375. <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required /></p>
  376. <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required /></p>
  377. <p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required /></p>
  378. <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
  379. ``as_ul()``
  380. -----------
  381. .. method:: Form.as_ul()
  382. ``as_ul()`` renders the form as a series of ``<li>`` tags, with each
  383. ``<li>`` containing one field. It does *not* include the ``<ul>`` or
  384. ``</ul>``, so that you can specify any HTML attributes on the ``<ul>`` for
  385. flexibility::
  386. >>> f = ContactForm()
  387. >>> f.as_ul()
  388. '<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required /></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>'
  389. >>> print(f.as_ul())
  390. <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required /></li>
  391. <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required /></li>
  392. <li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required /></li>
  393. <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>
  394. ``as_table()``
  395. --------------
  396. .. method:: Form.as_table()
  397. Finally, ``as_table()`` outputs the form as an HTML ``<table>``. This is
  398. exactly the same as ``print``. In fact, when you ``print`` a form object,
  399. it calls its ``as_table()`` method behind the scenes::
  400. >>> f = ContactForm()
  401. >>> f.as_table()
  402. '<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required /></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>'
  403. >>> print(f.as_table())
  404. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required /></td></tr>
  405. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required /></td></tr>
  406. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required /></td></tr>
  407. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
  408. .. _ref-forms-api-styling-form-rows:
  409. Styling required or erroneous form rows
  410. ---------------------------------------
  411. .. attribute:: Form.error_css_class
  412. .. attribute:: Form.required_css_class
  413. It's pretty common to style form rows and fields that are required or have
  414. errors. For example, you might want to present required form rows in bold and
  415. highlight errors in red.
  416. The :class:`Form` class has a couple of hooks you can use to add ``class``
  417. attributes to required rows or to rows with errors: simply set the
  418. :attr:`Form.error_css_class` and/or :attr:`Form.required_css_class`
  419. attributes::
  420. from django.forms import Form
  421. class ContactForm(Form):
  422. error_css_class = 'error'
  423. required_css_class = 'required'
  424. # ... and the rest of your fields here
  425. Once you've done that, rows will be given ``"error"`` and/or ``"required"``
  426. classes, as needed. The HTML will look something like::
  427. >>> f = ContactForm(data)
  428. >>> print(f.as_table())
  429. <tr class="required"><th><label class="required" for="id_subject">Subject:</label> ...
  430. <tr class="required"><th><label class="required" for="id_message">Message:</label> ...
  431. <tr class="required error"><th><label class="required" for="id_sender">Sender:</label> ...
  432. <tr><th><label for="id_cc_myself">Cc myself:<label> ...
  433. >>> f['subject'].label_tag()
  434. <label class="required" for="id_subject">Subject:</label>
  435. >>> f['subject'].label_tag(attrs={'class': 'foo'})
  436. <label for="id_subject" class="foo required">Subject:</label>
  437. .. _ref-forms-api-configuring-label:
  438. Configuring form elements' HTML ``id`` attributes and ``<label>`` tags
  439. ----------------------------------------------------------------------
  440. .. attribute:: Form.auto_id
  441. By default, the form rendering methods include:
  442. * HTML ``id`` attributes on the form elements.
  443. * The corresponding ``<label>`` tags around the labels. An HTML ``<label>`` tag
  444. designates which label text is associated with which form element. This small
  445. enhancement makes forms more usable and more accessible to assistive devices.
  446. It's always a good idea to use ``<label>`` tags.
  447. The ``id`` attribute values are generated by prepending ``id_`` to the form
  448. field names. This behavior is configurable, though, if you want to change the
  449. ``id`` convention or remove HTML ``id`` attributes and ``<label>`` tags
  450. entirely.
  451. Use the ``auto_id`` argument to the ``Form`` constructor to control the ``id``
  452. and label behavior. This argument must be ``True``, ``False`` or a string.
  453. If ``auto_id`` is ``False``, then the form output will not include ``<label>``
  454. tags nor ``id`` attributes::
  455. >>> f = ContactForm(auto_id=False)
  456. >>> print(f.as_table())
  457. <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required /></td></tr>
  458. <tr><th>Message:</th><td><input type="text" name="message" required /></td></tr>
  459. <tr><th>Sender:</th><td><input type="email" name="sender" required /></td></tr>
  460. <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
  461. >>> print(f.as_ul())
  462. <li>Subject: <input type="text" name="subject" maxlength="100" required /></li>
  463. <li>Message: <input type="text" name="message" required /></li>
  464. <li>Sender: <input type="email" name="sender" required /></li>
  465. <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
  466. >>> print(f.as_p())
  467. <p>Subject: <input type="text" name="subject" maxlength="100" required /></p>
  468. <p>Message: <input type="text" name="message" required /></p>
  469. <p>Sender: <input type="email" name="sender" required /></p>
  470. <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
  471. If ``auto_id`` is set to ``True``, then the form output *will* include
  472. ``<label>`` tags and will simply use the field name as its ``id`` for each form
  473. field::
  474. >>> f = ContactForm(auto_id=True)
  475. >>> print(f.as_table())
  476. <tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" required /></td></tr>
  477. <tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" required /></td></tr>
  478. <tr><th><label for="sender">Sender:</label></th><td><input type="email" name="sender" id="sender" required /></td></tr>
  479. <tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr>
  480. >>> print(f.as_ul())
  481. <li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" required /></li>
  482. <li><label for="message">Message:</label> <input type="text" name="message" id="message" required /></li>
  483. <li><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" required /></li>
  484. <li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li>
  485. >>> print(f.as_p())
  486. <p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" required /></p>
  487. <p><label for="message">Message:</label> <input type="text" name="message" id="message" required /></p>
  488. <p><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" required /></p>
  489. <p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></p>
  490. If ``auto_id`` is set to a string containing the format character ``'%s'``,
  491. then the form output will include ``<label>`` tags, and will generate ``id``
  492. attributes based on the format string. For example, for a format string
  493. ``'field_%s'``, a field named ``subject`` will get the ``id`` value
  494. ``'field_subject'``. Continuing our example::
  495. >>> f = ContactForm(auto_id='id_for_%s')
  496. >>> print(f.as_table())
  497. <tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" required /></td></tr>
  498. <tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" required /></td></tr>
  499. <tr><th><label for="id_for_sender">Sender:</label></th><td><input type="email" name="sender" id="id_for_sender" required /></td></tr>
  500. <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>
  501. >>> print(f.as_ul())
  502. <li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required /></li>
  503. <li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" required /></li>
  504. <li><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" required /></li>
  505. <li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
  506. >>> print(f.as_p())
  507. <p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required /></p>
  508. <p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" required /></p>
  509. <p><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" required /></p>
  510. <p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></p>
  511. If ``auto_id`` is set to any other true value -- such as a string that doesn't
  512. include ``%s`` -- then the library will act as if ``auto_id`` is ``True``.
  513. By default, ``auto_id`` is set to the string ``'id_%s'``.
  514. .. attribute:: Form.label_suffix
  515. A translatable string (defaults to a colon (``:``) in English) that will be
  516. appended after any label name when a form is rendered.
  517. It's possible to customize that character, or omit it entirely, using the
  518. ``label_suffix`` parameter::
  519. >>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
  520. >>> print(f.as_ul())
  521. <li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required /></li>
  522. <li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" required /></li>
  523. <li><label for="id_for_sender">Sender</label> <input type="email" name="sender" id="id_for_sender" required /></li>
  524. <li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
  525. >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
  526. >>> print(f.as_ul())
  527. <li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required /></li>
  528. <li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" required /></li>
  529. <li><label for="id_for_sender">Sender -></label> <input type="email" name="sender" id="id_for_sender" required /></li>
  530. <li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
  531. Note that the label suffix is added only if the last character of the
  532. label isn't a punctuation character (in English, those are ``.``, ``!``, ``?``
  533. or ``:``).
  534. Fields can also define their own :attr:`~django.forms.Field.label_suffix`.
  535. This will take precedence over :attr:`Form.label_suffix
  536. <django.forms.Form.label_suffix>`. The suffix can also be overridden at runtime
  537. using the ``label_suffix`` parameter to
  538. :meth:`~django.forms.BoundField.label_tag`.
  539. .. attribute:: Form.use_required_attribute
  540. .. versionadded:: 1.10
  541. When set to ``True`` (the default), required form fields will have the
  542. ``required`` HTML attribute.
  543. :doc:`Formsets </topics/forms/formsets>` instantiate forms with
  544. ``use_required_attribute=False`` to avoid incorrect browser validation when
  545. adding and deleting forms from a formset.
  546. Notes on field ordering
  547. -----------------------
  548. In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are
  549. displayed in the order in which you define them in your form class. For
  550. example, in the ``ContactForm`` example, the fields are defined in the order
  551. ``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML
  552. output, just change the order in which those fields are listed in the class.
  553. There are several other ways to customize the order:
  554. .. attribute:: Form.field_order
  555. .. versionadded:: 1.9
  556. By default ``Form.field_order=None``, which retains the order in which you
  557. define the fields in your form class. If ``field_order`` is a list of field
  558. names, the fields are ordered as specified by the list and remaining fields are
  559. appended according to the default order. Unknown field names in the list are
  560. ignored. This makes it possible to disable a field in a subclass by setting it
  561. to ``None`` without having to redefine ordering.
  562. You can also use the ``Form.field_order`` argument to a :class:`Form` to
  563. override the field order. If a :class:`~django.forms.Form` defines
  564. :attr:`~Form.field_order` *and* you include ``field_order`` when instantiating
  565. the ``Form``, then the latter ``field_order`` will have precedence.
  566. .. method:: Form.order_fields(field_order)
  567. .. versionadded:: 1.9
  568. You may rearrange the fields any time using ``order_fields()`` with a list of
  569. field names as in :attr:`~django.forms.Form.field_order`.
  570. How errors are displayed
  571. ------------------------
  572. If you render a bound ``Form`` object, the act of rendering will automatically
  573. run the form's validation if it hasn't already happened, and the HTML output
  574. will include the validation errors as a ``<ul class="errorlist">`` near the
  575. field. The particular positioning of the error messages depends on the output
  576. method you're using::
  577. >>> data = {'subject': '',
  578. ... 'message': 'Hi there',
  579. ... 'sender': 'invalid email address',
  580. ... 'cc_myself': True}
  581. >>> f = ContactForm(data, auto_id=False)
  582. >>> print(f.as_table())
  583. <tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" required /></td></tr>
  584. <tr><th>Message:</th><td><input type="text" name="message" value="Hi there" required /></td></tr>
  585. <tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid email address.</li></ul><input type="email" name="sender" value="invalid email address" required /></td></tr>
  586. <tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /></td></tr>
  587. >>> print(f.as_ul())
  588. <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" required /></li>
  589. <li>Message: <input type="text" name="message" value="Hi there" required /></li>
  590. <li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input type="email" name="sender" value="invalid email address" required /></li>
  591. <li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li>
  592. >>> print(f.as_p())
  593. <p><ul class="errorlist"><li>This field is required.</li></ul></p>
  594. <p>Subject: <input type="text" name="subject" maxlength="100" required /></p>
  595. <p>Message: <input type="text" name="message" value="Hi there" required /></p>
  596. <p><ul class="errorlist"><li>Enter a valid email address.</li></ul></p>
  597. <p>Sender: <input type="email" name="sender" value="invalid email address" required /></p>
  598. <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
  599. .. _ref-forms-error-list-format:
  600. Customizing the error list format
  601. ---------------------------------
  602. By default, forms use ``django.forms.utils.ErrorList`` to format validation
  603. errors. If you'd like to use an alternate class for displaying errors, you can
  604. pass that in at construction time (replace ``__str__`` by ``__unicode__`` on
  605. Python 2)::
  606. >>> from django.forms.utils import ErrorList
  607. >>> class DivErrorList(ErrorList):
  608. ... def __str__(self): # __unicode__ on Python 2
  609. ... return self.as_divs()
  610. ... def as_divs(self):
  611. ... if not self: return ''
  612. ... return '<div class="errorlist">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self])
  613. >>> f = ContactForm(data, auto_id=False, error_class=DivErrorList)
  614. >>> f.as_p()
  615. <div class="errorlist"><div class="error">This field is required.</div></div>
  616. <p>Subject: <input type="text" name="subject" maxlength="100" required /></p>
  617. <p>Message: <input type="text" name="message" value="Hi there" required /></p>
  618. <div class="errorlist"><div class="error">Enter a valid email address.</div></div>
  619. <p>Sender: <input type="email" name="sender" value="invalid email address" required /></p>
  620. <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
  621. More granular output
  622. ====================
  623. The ``as_p()``, ``as_ul()``, and ``as_table()`` methods are simply shortcuts --
  624. they're not the only way a form object can be displayed.
  625. .. class:: BoundField
  626. Used to display HTML or access attributes for a single field of a
  627. :class:`Form` instance.
  628. The ``__str__()`` (``__unicode__`` on Python 2) method of this
  629. object displays the HTML for this field.
  630. To retrieve a single ``BoundField``, use dictionary lookup syntax on your form
  631. using the field's name as the key::
  632. >>> form = ContactForm()
  633. >>> print(form['subject'])
  634. <input id="id_subject" type="text" name="subject" maxlength="100" required />
  635. To retrieve all ``BoundField`` objects, iterate the form::
  636. >>> form = ContactForm()
  637. >>> for boundfield in form: print(boundfield)
  638. <input id="id_subject" type="text" name="subject" maxlength="100" required />
  639. <input type="text" name="message" id="id_message" required />
  640. <input type="email" name="sender" id="id_sender" required />
  641. <input type="checkbox" name="cc_myself" id="id_cc_myself" />
  642. The field-specific output honors the form object's ``auto_id`` setting::
  643. >>> f = ContactForm(auto_id=False)
  644. >>> print(f['message'])
  645. <input type="text" name="message" required />
  646. >>> f = ContactForm(auto_id='id_%s')
  647. >>> print(f['message'])
  648. <input type="text" name="message" id="id_message" required />
  649. Attributes of ``BoundField``
  650. ----------------------------
  651. .. attribute:: BoundField.auto_id
  652. The HTML ID attribute for this ``BoundField``. Returns an empty string
  653. if :attr:`Form.auto_id` is ``False``.
  654. .. attribute:: BoundField.data
  655. This property returns the data for this :class:`~django.forms.BoundField`
  656. extracted by the widget's :meth:`~django.forms.Widget.value_from_datadict`
  657. method, or ``None`` if it wasn't given::
  658. >>> unbound_form = ContactForm()
  659. >>> print(unbound_form['subject'].data)
  660. None
  661. >>> bound_form = ContactForm(data={'subject': 'My Subject'})
  662. >>> print(bound_form['subject'].data)
  663. My Subject
  664. .. attribute:: BoundField.errors
  665. A :ref:`list-like object <ref-forms-error-list-format>` that is displayed
  666. as an HTML ``<ul class="errorlist">`` when printed::
  667. >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
  668. >>> f = ContactForm(data, auto_id=False)
  669. >>> print(f['message'])
  670. <input type="text" name="message" required />
  671. >>> f['message'].errors
  672. ['This field is required.']
  673. >>> print(f['message'].errors)
  674. <ul class="errorlist"><li>This field is required.</li></ul>
  675. >>> f['subject'].errors
  676. []
  677. >>> print(f['subject'].errors)
  678. >>> str(f['subject'].errors)
  679. ''
  680. .. attribute:: BoundField.field
  681. The form :class:`~django.forms.Field` instance from the form class that
  682. this :class:`~django.forms.BoundField` wraps.
  683. .. attribute:: BoundField.form
  684. The :class:`~django.forms.Form` instance this :class:`~django.forms.BoundField`
  685. is bound to.
  686. .. attribute:: BoundField.help_text
  687. The :attr:`~django.forms.Field.help_text` of the field.
  688. .. attribute:: BoundField.html_name
  689. The name that will be used in the widget's HTML ``name`` attribute. It takes
  690. the form :attr:`~django.forms.Form.prefix` into account.
  691. .. attribute:: BoundField.id_for_label
  692. Use this property to render the ID of this field. For example, if you are
  693. manually constructing a ``<label>`` in your template (despite the fact that
  694. :meth:`~BoundField.label_tag` will do this for you):
  695. .. code-block:: html+django
  696. <label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }}
  697. By default, this will be the field's name prefixed by ``id_``
  698. ("``id_my_field``" for the example above). You may modify the ID by setting
  699. :attr:`~django.forms.Widget.attrs` on the field's widget. For example,
  700. declaring a field like this::
  701. my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'}))
  702. and using the template above, would render something like:
  703. .. code-block:: html
  704. <label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" required />
  705. .. attribute:: BoundField.is_hidden
  706. Returns ``True`` if this :class:`~django.forms.BoundField`'s widget is
  707. hidden.
  708. .. attribute:: BoundField.label
  709. The :attr:`~django.forms.Field.label` of the field. This is used in
  710. :meth:`~BoundField.label_tag`.
  711. .. attribute:: BoundField.name
  712. The name of this field in the form::
  713. >>> f = ContactForm()
  714. >>> print(f['subject'].name)
  715. subject
  716. >>> print(f['message'].name)
  717. message
  718. Methods of ``BoundField``
  719. -------------------------
  720. .. method:: BoundField.as_hidden(attrs=None, **kwargs)
  721. Returns a string of HTML for representing this as an ``<input type="hidden">``.
  722. ``**kwargs`` are passed to :meth:`~django.forms.BoundField.as_widget`.
  723. This method is primarily used internally. You should use a widget instead.
  724. .. method:: BoundField.as_widget(widget=None, attrs=None, only_initial=False)
  725. Renders the field by rendering the passed widget, adding any HTML
  726. attributes passed as ``attrs``. If no widget is specified, then the
  727. field's default widget will be used.
  728. ``only_initial`` is used by Django internals and should not be set
  729. explicitly.
  730. .. method:: BoundField.css_classes()
  731. When you use Django's rendering shortcuts, CSS classes are used to
  732. indicate required form fields or fields that contain errors. If you're
  733. manually rendering a form, you can access these CSS classes using the
  734. ``css_classes`` method::
  735. >>> f = ContactForm(data={'message': ''})
  736. >>> f['message'].css_classes()
  737. 'required'
  738. If you want to provide some additional classes in addition to the
  739. error and required classes that may be required, you can provide
  740. those classes as an argument::
  741. >>> f = ContactForm(data={'message': ''})
  742. >>> f['message'].css_classes('foo bar')
  743. 'foo bar required'
  744. .. method:: BoundField.label_tag(contents=None, attrs=None, label_suffix=None)
  745. To separately render the label tag of a form field, you can call its
  746. ``label_tag()`` method::
  747. >>> f = ContactForm(data={'message': ''})
  748. >>> print(f['message'].label_tag())
  749. <label for="id_message">Message:</label>
  750. You can provide the ``contents`` parameter which will replace the
  751. auto-generated label tag. An ``attrs`` dictionary may contain additional
  752. attributes for the ``<label>`` tag.
  753. The HTML that's generated includes the form's
  754. :attr:`~django.forms.Form.label_suffix` (a colon, by default) or, if set, the
  755. current field's :attr:`~django.forms.Field.label_suffix`. The optional
  756. ``label_suffix`` parameter allows you to override any previously set
  757. suffix. For example, you can use an empty string to hide the label on selected
  758. fields. If you need to do this in a template, you could write a custom
  759. filter to allow passing parameters to ``label_tag``.
  760. .. method:: BoundField.value()
  761. Use this method to render the raw value of this field as it would be rendered
  762. by a ``Widget``::
  763. >>> initial = {'subject': 'welcome'}
  764. >>> unbound_form = ContactForm(initial=initial)
  765. >>> bound_form = ContactForm(data={'subject': 'hi'}, initial=initial)
  766. >>> print(unbound_form['subject'].value())
  767. welcome
  768. >>> print(bound_form['subject'].value())
  769. hi
  770. Customizing ``BoundField``
  771. ==========================
  772. .. versionadded:: 1.9
  773. If you need to access some additional information about a form field in a
  774. template and using a subclass of :class:`~django.forms.Field` isn't
  775. sufficient, consider also customizing :class:`~django.forms.BoundField`.
  776. A custom form field can override ``get_bound_field()``:
  777. .. method:: Field.get_bound_field(form, field_name)
  778. Takes an instance of :class:`~django.forms.Form` and the name of the field.
  779. The return value will be used when accessing the field in a template. Most
  780. likely it will be an instance of a subclass of
  781. :class:`~django.forms.BoundField`.
  782. If you have a ``GPSCoordinatesField``, for example, and want to be able to
  783. access additional information about the coordinates in a template, this could
  784. be implemented as follows::
  785. class GPSCoordinatesBoundField(BoundField):
  786. @property
  787. def country(self):
  788. """
  789. Return the country the coordinates lie in or None if it can't be
  790. determined.
  791. """
  792. value = self.value()
  793. if value:
  794. return get_country_from_coordinates(value)
  795. else:
  796. return None
  797. class GPSCoordinatesField(Field):
  798. def get_bound_field(self, form, field_name):
  799. return GPSCoordinatesBoundField(form, self, field_name)
  800. Now you can access the country in a template with
  801. ``{{ form.coordinates.country }}``.
  802. .. _binding-uploaded-files:
  803. Binding uploaded files to a form
  804. ================================
  805. Dealing with forms that have ``FileField`` and ``ImageField`` fields
  806. is a little more complicated than a normal form.
  807. Firstly, in order to upload files, you'll need to make sure that your
  808. ``<form>`` element correctly defines the ``enctype`` as
  809. ``"multipart/form-data"``::
  810. <form enctype="multipart/form-data" method="post" action="/foo/">
  811. Secondly, when you use the form, you need to bind the file data. File
  812. data is handled separately to normal form data, so when your form
  813. contains a ``FileField`` and ``ImageField``, you will need to specify
  814. a second argument when you bind your form. So if we extend our
  815. ContactForm to include an ``ImageField`` called ``mugshot``, we
  816. need to bind the file data containing the mugshot image::
  817. # Bound form with an image field
  818. >>> from django.core.files.uploadedfile import SimpleUploadedFile
  819. >>> data = {'subject': 'hello',
  820. ... 'message': 'Hi there',
  821. ... 'sender': 'foo@example.com',
  822. ... 'cc_myself': True}
  823. >>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)}
  824. >>> f = ContactFormWithMugshot(data, file_data)
  825. In practice, you will usually specify ``request.FILES`` as the source
  826. of file data (just like you use ``request.POST`` as the source of
  827. form data)::
  828. # Bound form with an image field, data from the request
  829. >>> f = ContactFormWithMugshot(request.POST, request.FILES)
  830. Constructing an unbound form is the same as always -- just omit both
  831. form data *and* file data::
  832. # Unbound form with an image field
  833. >>> f = ContactFormWithMugshot()
  834. Testing for multipart forms
  835. ---------------------------
  836. .. method:: Form.is_multipart()
  837. If you're writing reusable views or templates, you may not know ahead of time
  838. whether your form is a multipart form or not. The ``is_multipart()`` method
  839. tells you whether the form requires multipart encoding for submission::
  840. >>> f = ContactFormWithMugshot()
  841. >>> f.is_multipart()
  842. True
  843. Here's an example of how you might use this in a template::
  844. {% if form.is_multipart %}
  845. <form enctype="multipart/form-data" method="post" action="/foo/">
  846. {% else %}
  847. <form method="post" action="/foo/">
  848. {% endif %}
  849. {{ form }}
  850. </form>
  851. Subclassing forms
  852. =================
  853. If you have multiple ``Form`` classes that share fields, you can use
  854. subclassing to remove redundancy.
  855. When you subclass a custom ``Form`` class, the resulting subclass will
  856. include all fields of the parent class(es), followed by the fields you define
  857. in the subclass.
  858. In this example, ``ContactFormWithPriority`` contains all the fields from
  859. ``ContactForm``, plus an additional field, ``priority``. The ``ContactForm``
  860. fields are ordered first::
  861. >>> class ContactFormWithPriority(ContactForm):
  862. ... priority = forms.CharField()
  863. >>> f = ContactFormWithPriority(auto_id=False)
  864. >>> print(f.as_ul())
  865. <li>Subject: <input type="text" name="subject" maxlength="100" required /></li>
  866. <li>Message: <input type="text" name="message" required /></li>
  867. <li>Sender: <input type="email" name="sender" required /></li>
  868. <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
  869. <li>Priority: <input type="text" name="priority" required /></li>
  870. It's possible to subclass multiple forms, treating forms as mixins. In this
  871. example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``
  872. (in that order), and its field list includes the fields from the parent
  873. classes::
  874. >>> from django.forms import Form
  875. >>> class PersonForm(Form):
  876. ... first_name = CharField()
  877. ... last_name = CharField()
  878. >>> class InstrumentForm(Form):
  879. ... instrument = CharField()
  880. >>> class BeatleForm(PersonForm, InstrumentForm):
  881. ... haircut_type = CharField()
  882. >>> b = BeatleForm(auto_id=False)
  883. >>> print(b.as_ul())
  884. <li>First name: <input type="text" name="first_name" required /></li>
  885. <li>Last name: <input type="text" name="last_name" required /></li>
  886. <li>Instrument: <input type="text" name="instrument" required /></li>
  887. <li>Haircut type: <input type="text" name="haircut_type" required /></li>
  888. It's possible to declaratively remove a ``Field`` inherited from a parent class
  889. by setting the name of the field to ``None`` on the subclass. For example::
  890. >>> from django import forms
  891. >>> class ParentForm(forms.Form):
  892. ... name = forms.CharField()
  893. ... age = forms.IntegerField()
  894. >>> class ChildForm(ParentForm):
  895. ... name = None
  896. >>> ChildForm().fields.keys()
  897. ... ['age']
  898. .. _form-prefix:
  899. Prefixes for forms
  900. ==================
  901. .. attribute:: Form.prefix
  902. You can put several Django forms inside one ``<form>`` tag. To give each
  903. ``Form`` its own namespace, use the ``prefix`` keyword argument::
  904. >>> mother = PersonForm(prefix="mother")
  905. >>> father = PersonForm(prefix="father")
  906. >>> print(mother.as_ul())
  907. <li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" required /></li>
  908. <li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" required /></li>
  909. >>> print(father.as_ul())
  910. <li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" required /></li>
  911. <li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" required /></li>
  912. The prefix can also be specified on the form class::
  913. >>> class PersonForm(forms.Form):
  914. ... ...
  915. ... prefix = 'person'
  916. .. versionadded:: 1.9
  917. The ability to specify ``prefix`` on the form class was added.