api.txt 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  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, 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. 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. You can do this in JavaScript with ``element.textContent = errorText``
  119. or with jQuery's ``$(el).text(errorText)`` (rather than its ``.html()``
  120. function).
  121. If for some reason you don't want to use client-side escaping, you can also
  122. set ``escape_html=True`` and error messages will be escaped so you can use them
  123. directly in HTML.
  124. .. method:: Form.errors.get_json_data(escape_html=False)
  125. Returns the errors as a dictionary suitable for serializing to JSON.
  126. :meth:`Form.errors.as_json()` returns serialized JSON, while this returns the
  127. error data before it's serialized.
  128. The ``escape_html`` parameter behaves as described in
  129. :meth:`Form.errors.as_json()`.
  130. .. method:: Form.add_error(field, error)
  131. This method allows adding errors to specific fields from within the
  132. ``Form.clean()`` method, or from outside the form altogether; for instance
  133. from a view.
  134. The ``field`` argument is the name of the field to which the errors
  135. should be added. If its value is ``None`` the error will be treated as
  136. a non-field error as returned by :meth:`Form.non_field_errors()
  137. <django.forms.Form.non_field_errors>`.
  138. The ``error`` argument can be a string, or preferably an instance of
  139. ``ValidationError``. See :ref:`raising-validation-error` for best practices
  140. when defining form errors.
  141. Note that ``Form.add_error()`` automatically removes the relevant field from
  142. ``cleaned_data``.
  143. .. method:: Form.has_error(field, code=None)
  144. This method returns a boolean designating whether a field has an error with
  145. a specific error ``code``. If ``code`` is ``None``, it will return ``True``
  146. if the field contains any errors at all.
  147. To check for non-field errors use
  148. :data:`~django.core.exceptions.NON_FIELD_ERRORS` as the ``field`` parameter.
  149. .. method:: Form.non_field_errors()
  150. This method returns the list of errors from :attr:`Form.errors
  151. <django.forms.Form.errors>` that aren't associated with a particular field.
  152. This includes ``ValidationError``\s that are raised in :meth:`Form.clean()
  153. <django.forms.Form.clean>` and errors added using :meth:`Form.add_error(None,
  154. "...") <django.forms.Form.add_error>`.
  155. Behavior of unbound forms
  156. -------------------------
  157. It's meaningless to validate a form with no data, but, for the record, here's
  158. what happens with unbound forms::
  159. >>> f = ContactForm()
  160. >>> f.is_valid()
  161. False
  162. >>> f.errors
  163. {}
  164. .. _ref-forms-initial-form-values:
  165. Initial form values
  166. ===================
  167. .. attribute:: Form.initial
  168. Use :attr:`~Form.initial` to declare the initial value of form fields at
  169. runtime. For example, you might want to fill in a ``username`` field with the
  170. username of the current session.
  171. To accomplish this, use the :attr:`~Form.initial` argument to a :class:`Form`.
  172. This argument, if given, should be a dictionary mapping field names to initial
  173. values. Only include the fields for which you're specifying an initial value;
  174. it's not necessary to include every field in your form. For example::
  175. >>> f = ContactForm(initial={'subject': 'Hi there!'})
  176. These values are only displayed for unbound forms, and they're not used as
  177. fallback values if a particular value isn't provided.
  178. If a :class:`~django.forms.Field` defines :attr:`~Field.initial` *and* you
  179. include :attr:`~Form.initial` when instantiating the ``Form``, then the latter
  180. ``initial`` will have precedence. In this example, ``initial`` is provided both
  181. at the field level and at the form instance level, and the latter gets
  182. precedence::
  183. >>> from django import forms
  184. >>> class CommentForm(forms.Form):
  185. ... name = forms.CharField(initial='class')
  186. ... url = forms.URLField()
  187. ... comment = forms.CharField()
  188. >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
  189. >>> print(f)
  190. <tr><th>Name:</th><td><input type="text" name="name" value="instance" required></td></tr>
  191. <tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
  192. <tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
  193. .. method:: Form.get_initial_for_field(field, field_name)
  194. Returns the initial data for a form field. It retrieves the data from
  195. :attr:`Form.initial` if present, otherwise trying :attr:`Field.initial`.
  196. Callable values are evaluated.
  197. It is recommended to use :attr:`BoundField.initial` over
  198. :meth:`~Form.get_initial_for_field()` because ``BoundField.initial`` has a
  199. simpler interface. Also, unlike :meth:`~Form.get_initial_for_field()`,
  200. :attr:`BoundField.initial` caches its values. This is useful especially when
  201. dealing with callables whose return values can change (e.g. ``datetime.now`` or
  202. ``uuid.uuid4``)::
  203. >>> import uuid
  204. >>> class UUIDCommentForm(CommentForm):
  205. ... identifier = forms.UUIDField(initial=uuid.uuid4)
  206. >>> f = UUIDCommentForm()
  207. >>> f.get_initial_for_field(f.fields['identifier'], 'identifier')
  208. UUID('972ca9e4-7bfe-4f5b-af7d-07b3aa306334')
  209. >>> f.get_initial_for_field(f.fields['identifier'], 'identifier')
  210. UUID('1b411fab-844e-4dec-bd4f-e9b0495f04d0')
  211. >>> # Using BoundField.initial, for comparison
  212. >>> f['identifier'].initial
  213. UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
  214. >>> f['identifier'].initial
  215. UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
  216. Checking which form data has changed
  217. ====================================
  218. .. method:: Form.has_changed()
  219. Use the ``has_changed()`` method on your ``Form`` when you need to check if the
  220. form data has been changed from the initial data.
  221. >>> data = {'subject': 'hello',
  222. ... 'message': 'Hi there',
  223. ... 'sender': 'foo@example.com',
  224. ... 'cc_myself': True}
  225. >>> f = ContactForm(data, initial=data)
  226. >>> f.has_changed()
  227. False
  228. When the form is submitted, we reconstruct it and provide the original data
  229. so that the comparison can be done:
  230. >>> f = ContactForm(request.POST, initial=data)
  231. >>> f.has_changed()
  232. ``has_changed()`` will be ``True`` if the data from ``request.POST`` differs
  233. from what was provided in :attr:`~Form.initial` or ``False`` otherwise. The
  234. result is computed by calling :meth:`Field.has_changed` for each field in the
  235. form.
  236. .. attribute:: Form.changed_data
  237. The ``changed_data`` attribute returns a list of the names of the fields whose
  238. values in the form's bound data (usually ``request.POST``) differ from what was
  239. provided in :attr:`~Form.initial`. It returns an empty list if no data differs.
  240. >>> f = ContactForm(request.POST, initial=data)
  241. >>> if f.has_changed():
  242. ... print("The following fields changed: %s" % ", ".join(f.changed_data))
  243. >>> f.changed_data
  244. ['subject', 'message']
  245. Accessing the fields from the form
  246. ==================================
  247. .. attribute:: Form.fields
  248. You can access the fields of :class:`Form` instance from its ``fields``
  249. attribute::
  250. >>> for row in f.fields.values(): print(row)
  251. ...
  252. <django.forms.fields.CharField object at 0x7ffaac632510>
  253. <django.forms.fields.URLField object at 0x7ffaac632f90>
  254. <django.forms.fields.CharField object at 0x7ffaac3aa050>
  255. >>> f.fields['name']
  256. <django.forms.fields.CharField object at 0x7ffaac6324d0>
  257. You can alter the field of :class:`Form` instance to change the way it is
  258. presented in the form::
  259. >>> f.as_table().split('\n')[0]
  260. '<tr><th>Name:</th><td><input name="name" type="text" value="instance" required></td></tr>'
  261. >>> f.fields['name'].label = "Username"
  262. >>> f.as_table().split('\n')[0]
  263. '<tr><th>Username:</th><td><input name="name" type="text" value="instance" required></td></tr>'
  264. Beware not to alter the ``base_fields`` attribute because this modification
  265. will influence all subsequent ``ContactForm`` instances within the same Python
  266. process::
  267. >>> f.base_fields['name'].label = "Username"
  268. >>> another_f = CommentForm(auto_id=False)
  269. >>> another_f.as_table().split('\n')[0]
  270. '<tr><th>Username:</th><td><input name="name" type="text" value="class" required></td></tr>'
  271. Accessing "clean" data
  272. ======================
  273. .. attribute:: Form.cleaned_data
  274. Each field in a :class:`Form` class is responsible not only for validating
  275. data, but also for "cleaning" it -- normalizing it to a consistent format. This
  276. is a nice feature, because it allows data for a particular field to be input in
  277. a variety of ways, always resulting in consistent output.
  278. For example, :class:`~django.forms.DateField` normalizes input into a
  279. Python ``datetime.date`` object. Regardless of whether you pass it a string in
  280. the format ``'1994-07-15'``, a ``datetime.date`` object, or a number of other
  281. formats, ``DateField`` will always normalize it to a ``datetime.date`` object
  282. as long as it's valid.
  283. Once you've created a :class:`~Form` instance with a set of data and validated
  284. it, you can access the clean data via its ``cleaned_data`` attribute::
  285. >>> data = {'subject': 'hello',
  286. ... 'message': 'Hi there',
  287. ... 'sender': 'foo@example.com',
  288. ... 'cc_myself': True}
  289. >>> f = ContactForm(data)
  290. >>> f.is_valid()
  291. True
  292. >>> f.cleaned_data
  293. {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
  294. Note that any text-based field -- such as ``CharField`` or ``EmailField`` --
  295. always cleans the input into a string. We'll cover the encoding implications
  296. later in this document.
  297. If your data does *not* validate, the ``cleaned_data`` dictionary contains
  298. only the valid fields::
  299. >>> data = {'subject': '',
  300. ... 'message': 'Hi there',
  301. ... 'sender': 'invalid email address',
  302. ... 'cc_myself': True}
  303. >>> f = ContactForm(data)
  304. >>> f.is_valid()
  305. False
  306. >>> f.cleaned_data
  307. {'cc_myself': True, 'message': 'Hi there'}
  308. ``cleaned_data`` will always *only* contain a key for fields defined in the
  309. ``Form``, even if you pass extra data when you define the ``Form``. In this
  310. example, we pass a bunch of extra fields to the ``ContactForm`` constructor,
  311. but ``cleaned_data`` contains only the form's fields::
  312. >>> data = {'subject': 'hello',
  313. ... 'message': 'Hi there',
  314. ... 'sender': 'foo@example.com',
  315. ... 'cc_myself': True,
  316. ... 'extra_field_1': 'foo',
  317. ... 'extra_field_2': 'bar',
  318. ... 'extra_field_3': 'baz'}
  319. >>> f = ContactForm(data)
  320. >>> f.is_valid()
  321. True
  322. >>> f.cleaned_data # Doesn't contain extra_field_1, etc.
  323. {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
  324. When the ``Form`` is valid, ``cleaned_data`` will include a key and value for
  325. *all* its fields, even if the data didn't include a value for some optional
  326. fields. In this example, the data dictionary doesn't include a value for the
  327. ``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::
  328. >>> from django import forms
  329. >>> class OptionalPersonForm(forms.Form):
  330. ... first_name = forms.CharField()
  331. ... last_name = forms.CharField()
  332. ... nick_name = forms.CharField(required=False)
  333. >>> data = {'first_name': 'John', 'last_name': 'Lennon'}
  334. >>> f = OptionalPersonForm(data)
  335. >>> f.is_valid()
  336. True
  337. >>> f.cleaned_data
  338. {'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}
  339. In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an
  340. empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat
  341. empty values as an empty string. Each field type knows what its "blank" value
  342. is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For
  343. full details on each field's behavior in this case, see the "Empty value" note
  344. for each field in the "Built-in ``Field`` classes" section below.
  345. You can write code to perform validation for particular form fields (based on
  346. their name) or for the form as a whole (considering combinations of various
  347. fields). More information about this is in :doc:`/ref/forms/validation`.
  348. .. _ref-forms-api-outputting-html:
  349. Outputting forms as HTML
  350. ========================
  351. The second task of a ``Form`` object is to render itself as HTML. To do so,
  352. ``print`` it::
  353. >>> f = ContactForm()
  354. >>> print(f)
  355. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>
  356. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>
  357. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>
  358. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>
  359. If the form is bound to data, the HTML output will include that data
  360. appropriately. For example, if a field is represented by an
  361. ``<input type="text">``, the data will be in the ``value`` attribute. If a
  362. field is represented by an ``<input type="checkbox">``, then that HTML will
  363. include ``checked`` if appropriate::
  364. >>> data = {'subject': 'hello',
  365. ... 'message': 'Hi there',
  366. ... 'sender': 'foo@example.com',
  367. ... 'cc_myself': True}
  368. >>> f = ContactForm(data)
  369. >>> print(f)
  370. <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>
  371. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" required></td></tr>
  372. <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>
  373. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" checked></td></tr>
  374. This default output is a two-column HTML table, with a ``<tr>`` for each field.
  375. Notice the following:
  376. * For flexibility, the output does *not* include the ``<table>`` and
  377. ``</table>`` tags, nor does it include the ``<form>`` and ``</form>``
  378. tags or an ``<input type="submit">`` tag. It's your job to do that.
  379. * Each field type has a default HTML representation. ``CharField`` is
  380. represented by an ``<input type="text">`` and ``EmailField`` by an
  381. ``<input type="email">``. ``BooleanField(null=False)`` is represented by an
  382. ``<input type="checkbox">``. Note these are merely sensible defaults; you can
  383. specify which HTML to use for a given field by using widgets, which we'll
  384. explain shortly.
  385. * The HTML ``name`` for each tag is taken directly from its attribute name
  386. in the ``ContactForm`` class.
  387. * The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and
  388. ``'Cc myself:'`` is generated from the field name by converting all
  389. underscores to spaces and upper-casing the first letter. Again, note
  390. these are merely sensible defaults; you can also specify labels manually.
  391. * Each text label is surrounded in an HTML ``<label>`` tag, which points
  392. to the appropriate form field via its ``id``. Its ``id``, in turn, is
  393. generated by prepending ``'id_'`` to the field name. The ``id``
  394. attributes and ``<label>`` tags are included in the output by default, to
  395. follow best practices, but you can change that behavior.
  396. * The output uses HTML5 syntax, targeting ``<!DOCTYPE html>``. For example,
  397. it uses boolean attributes such as ``checked`` rather than the XHTML style
  398. of ``checked='checked'``.
  399. Although ``<table>`` output is the default output style when you ``print`` a
  400. form, other output styles are available. Each style is available as a method on
  401. a form object, and each rendering method returns a string.
  402. Default rendering
  403. -----------------
  404. The default rendering when you ``print`` a form uses the following methods and
  405. attributes.
  406. ``template_name``
  407. ~~~~~~~~~~~~~~~~~
  408. .. attribute:: Form.template_name
  409. The name of the template rendered if the form is cast into a string, e.g. via
  410. ``print(form)`` or in a template via ``{{ form }}``.
  411. By default, a property returning the value of the renderer's
  412. :attr:`~django.forms.renderers.BaseRenderer.form_template_name`. You may set it
  413. as a string template name in order to override that for a particular form
  414. class.
  415. .. versionchanged:: 4.1
  416. In older versions ``template_name`` defaulted to the string value
  417. ``'django/forms/default.html'``.
  418. ``render()``
  419. ~~~~~~~~~~~~
  420. .. method:: Form.render(template_name=None, context=None, renderer=None)
  421. The render method is called by ``__str__`` as well as the
  422. :meth:`.Form.as_table`, :meth:`.Form.as_p`, and :meth:`.Form.as_ul` methods.
  423. All arguments are optional and default to:
  424. * ``template_name``: :attr:`.Form.template_name`
  425. * ``context``: Value returned by :meth:`.Form.get_context`
  426. * ``renderer``: Value returned by :attr:`.Form.default_renderer`
  427. By passing ``template_name`` you can customize the template used for just a
  428. single call.
  429. ``get_context()``
  430. ~~~~~~~~~~~~~~~~~
  431. .. method:: Form.get_context()
  432. Return the template context for rendering the form.
  433. The available context is:
  434. * ``form``: The bound form.
  435. * ``fields``: All bound fields, except the hidden fields.
  436. * ``hidden_fields``: All hidden bound fields.
  437. * ``errors``: All non field related or hidden field related form errors.
  438. ``template_name_label``
  439. ~~~~~~~~~~~~~~~~~~~~~~~
  440. .. attribute:: Form.template_name_label
  441. The template used to render a field's ``<label>``, used when calling
  442. :meth:`BoundField.label_tag`/:meth:`~BoundField.legend_tag`. Can be changed per
  443. form by overriding this attribute or more generally by overriding the default
  444. template, see also :ref:`overriding-built-in-form-templates`.
  445. Output styles
  446. -------------
  447. As well as rendering the form directly, such as in a template with
  448. ``{{ form }}``, the following helper functions serve as a proxy to
  449. :meth:`Form.render` passing a particular ``template_name`` value.
  450. These helpers are most useful in a template, where you need to override the
  451. form renderer or form provided value but cannot pass the additional parameter
  452. to :meth:`~Form.render`. For example, you can render a form as an unordered
  453. list using ``{{ form.as_ul }}``.
  454. Each helper pairs a form method with an attribute giving the appropriate
  455. template name.
  456. ``as_div()``
  457. ~~~~~~~~~~~~
  458. .. attribute:: Form.template_name_div
  459. .. versionadded:: 4.1
  460. The template used by ``as_div()``. Default: ``'django/forms/div.html'``.
  461. .. method:: Form.as_div()
  462. .. versionadded:: 4.1
  463. ``as_div()`` renders the form as a series of ``<div>`` elements, with each
  464. ``<div>`` containing one field, such as:
  465. .. code-block:: pycon
  466. >>> f = ContactForm()
  467. >>> f.as_div()
  468. … gives HTML like:
  469. .. code-block:: html
  470. <div>
  471. <label for="id_subject">Subject:</label>
  472. <input type="text" name="subject" maxlength="100" required id="id_subject">
  473. </div>
  474. <div>
  475. <label for="id_message">Message:</label>
  476. <input type="text" name="message" required id="id_message">
  477. </div>
  478. <div>
  479. <label for="id_sender">Sender:</label>
  480. <input type="email" name="sender" required id="id_sender">
  481. </div>
  482. <div>
  483. <label for="id_cc_myself">Cc myself:</label>
  484. <input type="checkbox" name="cc_myself" id="id_cc_myself">
  485. </div>
  486. .. note::
  487. Of the framework provided templates and output styles, ``as_div()`` is
  488. recommended over the ``as_p()``, ``as_table()``, and ``as_ul()`` versions
  489. as the template implements ``<fieldset>`` and ``<legend>`` to group related
  490. inputs and is easier for screen reader users to navigate.
  491. ``as_p()``
  492. ~~~~~~~~~~
  493. .. attribute:: Form.template_name_p
  494. The template used by ``as_p()``. Default: ``'django/forms/p.html'``.
  495. .. method:: Form.as_p()
  496. ``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
  497. containing one field::
  498. >>> f = ContactForm()
  499. >>> f.as_p()
  500. '<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>'
  501. >>> print(f.as_p())
  502. <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>
  503. <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>
  504. <p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></p>
  505. <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>
  506. ``as_ul()``
  507. ~~~~~~~~~~~
  508. .. attribute:: Form.template_name_ul
  509. The template used by ``as_ul()``. Default: ``'django/forms/ul.html'``.
  510. .. method:: Form.as_ul()
  511. ``as_ul()`` renders the form as a series of ``<li>`` tags, with each ``<li>``
  512. containing one field. It does *not* include the ``<ul>`` or ``</ul>``, so that
  513. you can specify any HTML attributes on the ``<ul>`` for flexibility::
  514. >>> f = ContactForm()
  515. >>> f.as_ul()
  516. '<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>'
  517. >>> print(f.as_ul())
  518. <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>
  519. <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>
  520. <li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>
  521. <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>
  522. ``as_table()``
  523. ~~~~~~~~~~~~~~
  524. .. attribute:: Form.template_name_table
  525. The template used by ``as_table()``. Default: ``'django/forms/table.html'``.
  526. .. method:: Form.as_table()
  527. ``as_table()`` renders the form as an HTML ``<table>``::
  528. >>> f = ContactForm()
  529. >>> f.as_table()
  530. '<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>'
  531. >>> print(f)
  532. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>
  533. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>
  534. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>
  535. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>
  536. .. _ref-forms-api-styling-form-rows:
  537. Styling required or erroneous form rows
  538. ---------------------------------------
  539. .. attribute:: Form.error_css_class
  540. .. attribute:: Form.required_css_class
  541. It's pretty common to style form rows and fields that are required or have
  542. errors. For example, you might want to present required form rows in bold and
  543. highlight errors in red.
  544. The :class:`Form` class has a couple of hooks you can use to add ``class``
  545. attributes to required rows or to rows with errors: set the
  546. :attr:`Form.error_css_class` and/or :attr:`Form.required_css_class`
  547. attributes::
  548. from django import forms
  549. class ContactForm(forms.Form):
  550. error_css_class = 'error'
  551. required_css_class = 'required'
  552. # ... and the rest of your fields here
  553. Once you've done that, rows will be given ``"error"`` and/or ``"required"``
  554. classes, as needed. The HTML will look something like::
  555. >>> f = ContactForm(data)
  556. >>> print(f.as_table())
  557. <tr class="required"><th><label class="required" for="id_subject">Subject:</label> ...
  558. <tr class="required"><th><label class="required" for="id_message">Message:</label> ...
  559. <tr class="required error"><th><label class="required" for="id_sender">Sender:</label> ...
  560. <tr><th><label for="id_cc_myself">Cc myself:<label> ...
  561. >>> f['subject'].label_tag()
  562. <label class="required" for="id_subject">Subject:</label>
  563. >>> f['subject'].legend_tag()
  564. <legend class="required" for="id_subject">Subject:</legend>
  565. >>> f['subject'].label_tag(attrs={'class': 'foo'})
  566. <label for="id_subject" class="foo required">Subject:</label>
  567. >>> f['subject'].legend_tag(attrs={'class': 'foo'})
  568. <legend for="id_subject" class="foo required">Subject:</legend>
  569. .. _ref-forms-api-configuring-label:
  570. Configuring form elements' HTML ``id`` attributes and ``<label>`` tags
  571. ----------------------------------------------------------------------
  572. .. attribute:: Form.auto_id
  573. By default, the form rendering methods include:
  574. * HTML ``id`` attributes on the form elements.
  575. * The corresponding ``<label>`` tags around the labels. An HTML ``<label>`` tag
  576. designates which label text is associated with which form element. This small
  577. enhancement makes forms more usable and more accessible to assistive devices.
  578. It's always a good idea to use ``<label>`` tags.
  579. The ``id`` attribute values are generated by prepending ``id_`` to the form
  580. field names. This behavior is configurable, though, if you want to change the
  581. ``id`` convention or remove HTML ``id`` attributes and ``<label>`` tags
  582. entirely.
  583. Use the ``auto_id`` argument to the ``Form`` constructor to control the ``id``
  584. and label behavior. This argument must be ``True``, ``False`` or a string.
  585. If ``auto_id`` is ``False``, then the form output will not include ``<label>``
  586. tags nor ``id`` attributes::
  587. >>> f = ContactForm(auto_id=False)
  588. >>> print(f.as_table())
  589. <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required></td></tr>
  590. <tr><th>Message:</th><td><input type="text" name="message" required></td></tr>
  591. <tr><th>Sender:</th><td><input type="email" name="sender" required></td></tr>
  592. <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself"></td></tr>
  593. >>> print(f.as_ul())
  594. <li>Subject: <input type="text" name="subject" maxlength="100" required></li>
  595. <li>Message: <input type="text" name="message" required></li>
  596. <li>Sender: <input type="email" name="sender" required></li>
  597. <li>Cc myself: <input type="checkbox" name="cc_myself"></li>
  598. >>> print(f.as_p())
  599. <p>Subject: <input type="text" name="subject" maxlength="100" required></p>
  600. <p>Message: <input type="text" name="message" required></p>
  601. <p>Sender: <input type="email" name="sender" required></p>
  602. <p>Cc myself: <input type="checkbox" name="cc_myself"></p>
  603. If ``auto_id`` is set to ``True``, then the form output *will* include
  604. ``<label>`` tags and will use the field name as its ``id`` for each form
  605. field::
  606. >>> f = ContactForm(auto_id=True)
  607. >>> print(f.as_table())
  608. <tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" required></td></tr>
  609. <tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" required></td></tr>
  610. <tr><th><label for="sender">Sender:</label></th><td><input type="email" name="sender" id="sender" required></td></tr>
  611. <tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself"></td></tr>
  612. >>> print(f.as_ul())
  613. <li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" required></li>
  614. <li><label for="message">Message:</label> <input type="text" name="message" id="message" required></li>
  615. <li><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" required></li>
  616. <li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself"></li>
  617. >>> print(f.as_p())
  618. <p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" required></p>
  619. <p><label for="message">Message:</label> <input type="text" name="message" id="message" required></p>
  620. <p><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" required></p>
  621. <p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself"></p>
  622. If ``auto_id`` is set to a string containing the format character ``'%s'``,
  623. then the form output will include ``<label>`` tags, and will generate ``id``
  624. attributes based on the format string. For example, for a format string
  625. ``'field_%s'``, a field named ``subject`` will get the ``id`` value
  626. ``'field_subject'``. Continuing our example::
  627. >>> f = ContactForm(auto_id='id_for_%s')
  628. >>> print(f.as_table())
  629. <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>
  630. <tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" required></td></tr>
  631. <tr><th><label for="id_for_sender">Sender:</label></th><td><input type="email" name="sender" id="id_for_sender" required></td></tr>
  632. <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>
  633. >>> print(f.as_ul())
  634. <li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></li>
  635. <li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" required></li>
  636. <li><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" required></li>
  637. <li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></li>
  638. >>> print(f.as_p())
  639. <p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></p>
  640. <p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" required></p>
  641. <p><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" required></p>
  642. <p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></p>
  643. If ``auto_id`` is set to any other true value -- such as a string that doesn't
  644. include ``%s`` -- then the library will act as if ``auto_id`` is ``True``.
  645. By default, ``auto_id`` is set to the string ``'id_%s'``.
  646. .. attribute:: Form.label_suffix
  647. A translatable string (defaults to a colon (``:``) in English) that will be
  648. appended after any label name when a form is rendered.
  649. It's possible to customize that character, or omit it entirely, using the
  650. ``label_suffix`` parameter::
  651. >>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
  652. >>> print(f.as_ul())
  653. <li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></li>
  654. <li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" required></li>
  655. <li><label for="id_for_sender">Sender</label> <input type="email" name="sender" id="id_for_sender" required></li>
  656. <li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></li>
  657. >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
  658. >>> print(f.as_ul())
  659. <li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></li>
  660. <li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" required></li>
  661. <li><label for="id_for_sender">Sender -></label> <input type="email" name="sender" id="id_for_sender" required></li>
  662. <li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></li>
  663. Note that the label suffix is added only if the last character of the
  664. label isn't a punctuation character (in English, those are ``.``, ``!``, ``?``
  665. or ``:``).
  666. Fields can also define their own :attr:`~django.forms.Field.label_suffix`.
  667. This will take precedence over :attr:`Form.label_suffix
  668. <django.forms.Form.label_suffix>`. The suffix can also be overridden at runtime
  669. using the ``label_suffix`` parameter to
  670. :meth:`~django.forms.BoundField.label_tag`/
  671. :meth:`~django.forms.BoundField.legend_tag`.
  672. .. attribute:: Form.use_required_attribute
  673. When set to ``True`` (the default), required form fields will have the
  674. ``required`` HTML attribute.
  675. :doc:`Formsets </topics/forms/formsets>` instantiate forms with
  676. ``use_required_attribute=False`` to avoid incorrect browser validation when
  677. adding and deleting forms from a formset.
  678. Configuring the rendering of a form's widgets
  679. ---------------------------------------------
  680. .. attribute:: Form.default_renderer
  681. Specifies the :doc:`renderer <renderers>` to use for the form. Defaults to
  682. ``None`` which means to use the default renderer specified by the
  683. :setting:`FORM_RENDERER` setting.
  684. You can set this as a class attribute when declaring your form or use the
  685. ``renderer`` argument to ``Form.__init__()``. For example::
  686. from django import forms
  687. class MyForm(forms.Form):
  688. default_renderer = MyRenderer()
  689. or::
  690. form = MyForm(renderer=MyRenderer())
  691. Notes on field ordering
  692. -----------------------
  693. In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are
  694. displayed in the order in which you define them in your form class. For
  695. example, in the ``ContactForm`` example, the fields are defined in the order
  696. ``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML
  697. output, change the order in which those fields are listed in the class.
  698. There are several other ways to customize the order:
  699. .. attribute:: Form.field_order
  700. By default ``Form.field_order=None``, which retains the order in which you
  701. define the fields in your form class. If ``field_order`` is a list of field
  702. names, the fields are ordered as specified by the list and remaining fields are
  703. appended according to the default order. Unknown field names in the list are
  704. ignored. This makes it possible to disable a field in a subclass by setting it
  705. to ``None`` without having to redefine ordering.
  706. You can also use the ``Form.field_order`` argument to a :class:`Form` to
  707. override the field order. If a :class:`~django.forms.Form` defines
  708. :attr:`~Form.field_order` *and* you include ``field_order`` when instantiating
  709. the ``Form``, then the latter ``field_order`` will have precedence.
  710. .. method:: Form.order_fields(field_order)
  711. You may rearrange the fields any time using ``order_fields()`` with a list of
  712. field names as in :attr:`~django.forms.Form.field_order`.
  713. How errors are displayed
  714. ------------------------
  715. If you render a bound ``Form`` object, the act of rendering will automatically
  716. run the form's validation if it hasn't already happened, and the HTML output
  717. will include the validation errors as a ``<ul class="errorlist">`` near the
  718. field. The particular positioning of the error messages depends on the output
  719. method you're using::
  720. >>> data = {'subject': '',
  721. ... 'message': 'Hi there',
  722. ... 'sender': 'invalid email address',
  723. ... 'cc_myself': True}
  724. >>> f = ContactForm(data, auto_id=False)
  725. >>> print(f.as_table())
  726. <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>
  727. <tr><th>Message:</th><td><input type="text" name="message" value="Hi there" required></td></tr>
  728. <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>
  729. <tr><th>Cc myself:</th><td><input checked type="checkbox" name="cc_myself"></td></tr>
  730. >>> print(f.as_ul())
  731. <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" required></li>
  732. <li>Message: <input type="text" name="message" value="Hi there" required></li>
  733. <li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input type="email" name="sender" value="invalid email address" required></li>
  734. <li>Cc myself: <input checked type="checkbox" name="cc_myself"></li>
  735. >>> print(f.as_p())
  736. <p><ul class="errorlist"><li>This field is required.</li></ul></p>
  737. <p>Subject: <input type="text" name="subject" maxlength="100" required></p>
  738. <p>Message: <input type="text" name="message" value="Hi there" required></p>
  739. <p><ul class="errorlist"><li>Enter a valid email address.</li></ul></p>
  740. <p>Sender: <input type="email" name="sender" value="invalid email address" required></p>
  741. <p>Cc myself: <input checked type="checkbox" name="cc_myself"></p>
  742. .. _ref-forms-error-list-format:
  743. Customizing the error list format
  744. ---------------------------------
  745. .. class:: ErrorList(initlist=None, error_class=None, renderer=None)
  746. By default, forms use ``django.forms.utils.ErrorList`` to format validation
  747. errors. ``ErrorList`` is a list like object where ``initlist`` is the
  748. list of errors. In addition this class has the following attributes and
  749. methods.
  750. .. attribute:: error_class
  751. The CSS classes to be used when rendering the error list. Any provided
  752. classes are added to the default ``errorlist`` class.
  753. .. attribute:: renderer
  754. Specifies the :doc:`renderer <renderers>` to use for ``ErrorList``.
  755. Defaults to ``None`` which means to use the default renderer
  756. specified by the :setting:`FORM_RENDERER` setting.
  757. .. attribute:: template_name
  758. The name of the template used when calling ``__str__`` or
  759. :meth:`render`. By default this is
  760. ``'django/forms/errors/list/default.html'`` which is a proxy for the
  761. ``'ul.html'`` template.
  762. .. attribute:: template_name_text
  763. The name of the template used when calling :meth:`.as_text`. By default
  764. this is ``'django/forms/errors/list/text.html'``. This template renders
  765. the errors as a list of bullet points.
  766. .. attribute:: template_name_ul
  767. The name of the template used when calling :meth:`.as_ul`. By default
  768. this is ``'django/forms/errors/list/ul.html'``. This template renders
  769. the errors in ``<li>`` tags with a wrapping ``<ul>`` with the CSS
  770. classes as defined by :attr:`.error_class`.
  771. .. method:: get_context()
  772. Return context for rendering of errors in a template.
  773. The available context is:
  774. * ``errors`` : A list of the errors.
  775. * ``error_class`` : A string of CSS classes.
  776. .. method:: render(template_name=None, context=None, renderer=None)
  777. The render method is called by ``__str__`` as well as by the
  778. :meth:`.as_ul` method.
  779. All arguments are optional and will default to:
  780. * ``template_name``: Value returned by :attr:`.template_name`
  781. * ``context``: Value returned by :meth:`.get_context`
  782. * ``renderer``: Value returned by :attr:`.renderer`
  783. .. method:: as_text()
  784. Renders the error list using the template defined by
  785. :attr:`.template_name_text`.
  786. .. method:: as_ul()
  787. Renders the error list using the template defined by
  788. :attr:`.template_name_ul`.
  789. If you'd like to customize the rendering of errors this can be achieved by
  790. overriding the :attr:`.template_name` attribute or more generally by
  791. overriding the default template, see also
  792. :ref:`overriding-built-in-form-templates`.
  793. .. deprecated:: 4.0
  794. The ability to return a ``str`` when calling the ``__str__`` method is
  795. deprecated. Use the template engine instead which returns a ``SafeString``.
  796. More granular output
  797. ====================
  798. The ``as_p()``, ``as_ul()``, and ``as_table()`` methods are shortcuts --
  799. they're not the only way a form object can be displayed.
  800. .. class:: BoundField
  801. Used to display HTML or access attributes for a single field of a
  802. :class:`Form` instance.
  803. The ``__str__()`` method of this object displays the HTML for this field.
  804. To retrieve a single ``BoundField``, use dictionary lookup syntax on your form
  805. using the field's name as the key::
  806. >>> form = ContactForm()
  807. >>> print(form['subject'])
  808. <input id="id_subject" type="text" name="subject" maxlength="100" required>
  809. To retrieve all ``BoundField`` objects, iterate the form::
  810. >>> form = ContactForm()
  811. >>> for boundfield in form: print(boundfield)
  812. <input id="id_subject" type="text" name="subject" maxlength="100" required>
  813. <input type="text" name="message" id="id_message" required>
  814. <input type="email" name="sender" id="id_sender" required>
  815. <input type="checkbox" name="cc_myself" id="id_cc_myself">
  816. The field-specific output honors the form object's ``auto_id`` setting::
  817. >>> f = ContactForm(auto_id=False)
  818. >>> print(f['message'])
  819. <input type="text" name="message" required>
  820. >>> f = ContactForm(auto_id='id_%s')
  821. >>> print(f['message'])
  822. <input type="text" name="message" id="id_message" required>
  823. Attributes of ``BoundField``
  824. ----------------------------
  825. .. attribute:: BoundField.auto_id
  826. The HTML ID attribute for this ``BoundField``. Returns an empty string
  827. if :attr:`Form.auto_id` is ``False``.
  828. .. attribute:: BoundField.data
  829. This property returns the data for this :class:`~django.forms.BoundField`
  830. extracted by the widget's :meth:`~django.forms.Widget.value_from_datadict`
  831. method, or ``None`` if it wasn't given::
  832. >>> unbound_form = ContactForm()
  833. >>> print(unbound_form['subject'].data)
  834. None
  835. >>> bound_form = ContactForm(data={'subject': 'My Subject'})
  836. >>> print(bound_form['subject'].data)
  837. My Subject
  838. .. attribute:: BoundField.errors
  839. A :ref:`list-like object <ref-forms-error-list-format>` that is displayed
  840. as an HTML ``<ul class="errorlist">`` when printed::
  841. >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
  842. >>> f = ContactForm(data, auto_id=False)
  843. >>> print(f['message'])
  844. <input type="text" name="message" required>
  845. >>> f['message'].errors
  846. ['This field is required.']
  847. >>> print(f['message'].errors)
  848. <ul class="errorlist"><li>This field is required.</li></ul>
  849. >>> f['subject'].errors
  850. []
  851. >>> print(f['subject'].errors)
  852. >>> str(f['subject'].errors)
  853. ''
  854. .. attribute:: BoundField.field
  855. The form :class:`~django.forms.Field` instance from the form class that
  856. this :class:`~django.forms.BoundField` wraps.
  857. .. attribute:: BoundField.form
  858. The :class:`~django.forms.Form` instance this :class:`~django.forms.BoundField`
  859. is bound to.
  860. .. attribute:: BoundField.help_text
  861. The :attr:`~django.forms.Field.help_text` of the field.
  862. .. attribute:: BoundField.html_name
  863. The name that will be used in the widget's HTML ``name`` attribute. It takes
  864. the form :attr:`~django.forms.Form.prefix` into account.
  865. .. attribute:: BoundField.id_for_label
  866. Use this property to render the ID of this field. For example, if you are
  867. manually constructing a ``<label>`` in your template (despite the fact that
  868. :meth:`~BoundField.label_tag`/:meth:`~BoundField.legend_tag` will do this
  869. for you):
  870. .. code-block:: html+django
  871. <label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }}
  872. By default, this will be the field's name prefixed by ``id_``
  873. ("``id_my_field``" for the example above). You may modify the ID by setting
  874. :attr:`~django.forms.Widget.attrs` on the field's widget. For example,
  875. declaring a field like this::
  876. my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'}))
  877. and using the template above, would render something like:
  878. .. code-block:: html
  879. <label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" required>
  880. .. attribute:: BoundField.initial
  881. Use :attr:`BoundField.initial` to retrieve initial data for a form field.
  882. It retrieves the data from :attr:`Form.initial` if present, otherwise
  883. trying :attr:`Field.initial`. Callable values are evaluated. See
  884. :ref:`ref-forms-initial-form-values` for more examples.
  885. :attr:`BoundField.initial` caches its return value, which is useful
  886. especially when dealing with callables whose return values can change (e.g.
  887. ``datetime.now`` or ``uuid.uuid4``)::
  888. >>> from datetime import datetime
  889. >>> class DatedCommentForm(CommentForm):
  890. ... created = forms.DateTimeField(initial=datetime.now)
  891. >>> f = DatedCommentForm()
  892. >>> f['created'].initial
  893. datetime.datetime(2021, 7, 27, 9, 5, 54)
  894. >>> f['created'].initial
  895. datetime.datetime(2021, 7, 27, 9, 5, 54)
  896. Using :attr:`BoundField.initial` is recommended over
  897. :meth:`~Form.get_initial_for_field()`.
  898. .. attribute:: BoundField.is_hidden
  899. Returns ``True`` if this :class:`~django.forms.BoundField`'s widget is
  900. hidden.
  901. .. attribute:: BoundField.label
  902. The :attr:`~django.forms.Field.label` of the field. This is used in
  903. :meth:`~BoundField.label_tag`/:meth:`~BoundField.legend_tag`.
  904. .. attribute:: BoundField.name
  905. The name of this field in the form::
  906. >>> f = ContactForm()
  907. >>> print(f['subject'].name)
  908. subject
  909. >>> print(f['message'].name)
  910. message
  911. .. attribute:: BoundField.use_fieldset
  912. .. versionadded:: 4.1
  913. Returns the value of this BoundField widget's ``use_fieldset`` attribute.
  914. .. attribute:: BoundField.widget_type
  915. Returns the lowercased class name of the wrapped field's widget, with any
  916. trailing ``input`` or ``widget`` removed. This may be used when building
  917. forms where the layout is dependent upon the widget type. For example::
  918. {% for field in form %}
  919. {% if field.widget_type == 'checkbox' %}
  920. # render one way
  921. {% else %}
  922. # render another way
  923. {% endif %}
  924. {% endfor %}
  925. Methods of ``BoundField``
  926. -------------------------
  927. .. method:: BoundField.as_hidden(attrs=None, **kwargs)
  928. Returns a string of HTML for representing this as an ``<input type="hidden">``.
  929. ``**kwargs`` are passed to :meth:`~django.forms.BoundField.as_widget`.
  930. This method is primarily used internally. You should use a widget instead.
  931. .. method:: BoundField.as_widget(widget=None, attrs=None, only_initial=False)
  932. Renders the field by rendering the passed widget, adding any HTML
  933. attributes passed as ``attrs``. If no widget is specified, then the
  934. field's default widget will be used.
  935. ``only_initial`` is used by Django internals and should not be set
  936. explicitly.
  937. .. method:: BoundField.css_classes(extra_classes=None)
  938. When you use Django's rendering shortcuts, CSS classes are used to
  939. indicate required form fields or fields that contain errors. If you're
  940. manually rendering a form, you can access these CSS classes using the
  941. ``css_classes`` method::
  942. >>> f = ContactForm(data={'message': ''})
  943. >>> f['message'].css_classes()
  944. 'required'
  945. If you want to provide some additional classes in addition to the
  946. error and required classes that may be required, you can provide
  947. those classes as an argument::
  948. >>> f = ContactForm(data={'message': ''})
  949. >>> f['message'].css_classes('foo bar')
  950. 'foo bar required'
  951. .. method:: BoundField.label_tag(contents=None, attrs=None, label_suffix=None, tag=None)
  952. Renders a label tag for the form field using the template specified by
  953. :attr:`.Form.template_name_label`.
  954. The available context is:
  955. * ``field``: This instance of the :class:`BoundField`.
  956. * ``contents``: By default a concatenated string of
  957. :attr:`BoundField.label` and :attr:`Form.label_suffix` (or
  958. :attr:`Field.label_suffix`, if set). This can be overridden by the
  959. ``contents`` and ``label_suffix`` arguments.
  960. * ``attrs``: A ``dict`` containing ``for``,
  961. :attr:`Form.required_css_class`, and ``id``. ``id`` is generated by the
  962. field's widget ``attrs`` or :attr:`BoundField.auto_id`. Additional
  963. attributes can be provided by the ``attrs`` argument.
  964. * ``use_tag``: A boolean which is ``True`` if the label has an ``id``.
  965. If ``False`` the default template omits the ``tag``.
  966. * ``tag``: An optional string to customize the tag, defaults to ``label``.
  967. .. tip::
  968. In your template ``field`` is the instance of the ``BoundField``.
  969. Therefore ``field.field`` accesses :attr:`BoundField.field` being
  970. the field you declare, e.g. ``forms.CharField``.
  971. To separately render the label tag of a form field, you can call its
  972. ``label_tag()`` method::
  973. >>> f = ContactForm(data={'message': ''})
  974. >>> print(f['message'].label_tag())
  975. <label for="id_message">Message:</label>
  976. If you'd like to customize the rendering this can be achieved by overriding
  977. the :attr:`.Form.template_name_label` attribute or more generally by
  978. overriding the default template, see also
  979. :ref:`overriding-built-in-form-templates`.
  980. .. versionchanged:: 4.1
  981. The ``tag`` argument was added.
  982. .. method:: BoundField.legend_tag(contents=None, attrs=None, label_suffix=None)
  983. .. versionadded:: 4.1
  984. Calls :meth:`.label_tag` with ``tag='legend'`` to render the label with
  985. ``<legend>`` tags. This is useful when rendering radio and multiple
  986. checkbox widgets where ``<legend>`` may be more appropriate than a
  987. ``<label>``.
  988. .. method:: BoundField.value()
  989. Use this method to render the raw value of this field as it would be rendered
  990. by a ``Widget``::
  991. >>> initial = {'subject': 'welcome'}
  992. >>> unbound_form = ContactForm(initial=initial)
  993. >>> bound_form = ContactForm(data={'subject': 'hi'}, initial=initial)
  994. >>> print(unbound_form['subject'].value())
  995. welcome
  996. >>> print(bound_form['subject'].value())
  997. hi
  998. Customizing ``BoundField``
  999. ==========================
  1000. If you need to access some additional information about a form field in a
  1001. template and using a subclass of :class:`~django.forms.Field` isn't
  1002. sufficient, consider also customizing :class:`~django.forms.BoundField`.
  1003. A custom form field can override ``get_bound_field()``:
  1004. .. method:: Field.get_bound_field(form, field_name)
  1005. Takes an instance of :class:`~django.forms.Form` and the name of the field.
  1006. The return value will be used when accessing the field in a template. Most
  1007. likely it will be an instance of a subclass of
  1008. :class:`~django.forms.BoundField`.
  1009. If you have a ``GPSCoordinatesField``, for example, and want to be able to
  1010. access additional information about the coordinates in a template, this could
  1011. be implemented as follows::
  1012. class GPSCoordinatesBoundField(BoundField):
  1013. @property
  1014. def country(self):
  1015. """
  1016. Return the country the coordinates lie in or None if it can't be
  1017. determined.
  1018. """
  1019. value = self.value()
  1020. if value:
  1021. return get_country_from_coordinates(value)
  1022. else:
  1023. return None
  1024. class GPSCoordinatesField(Field):
  1025. def get_bound_field(self, form, field_name):
  1026. return GPSCoordinatesBoundField(form, self, field_name)
  1027. Now you can access the country in a template with
  1028. ``{{ form.coordinates.country }}``.
  1029. .. _binding-uploaded-files:
  1030. Binding uploaded files to a form
  1031. ================================
  1032. Dealing with forms that have ``FileField`` and ``ImageField`` fields
  1033. is a little more complicated than a normal form.
  1034. Firstly, in order to upload files, you'll need to make sure that your
  1035. ``<form>`` element correctly defines the ``enctype`` as
  1036. ``"multipart/form-data"``::
  1037. <form enctype="multipart/form-data" method="post" action="/foo/">
  1038. Secondly, when you use the form, you need to bind the file data. File
  1039. data is handled separately to normal form data, so when your form
  1040. contains a ``FileField`` and ``ImageField``, you will need to specify
  1041. a second argument when you bind your form. So if we extend our
  1042. ContactForm to include an ``ImageField`` called ``mugshot``, we
  1043. need to bind the file data containing the mugshot image::
  1044. # Bound form with an image field
  1045. >>> from django.core.files.uploadedfile import SimpleUploadedFile
  1046. >>> data = {'subject': 'hello',
  1047. ... 'message': 'Hi there',
  1048. ... 'sender': 'foo@example.com',
  1049. ... 'cc_myself': True}
  1050. >>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)}
  1051. >>> f = ContactFormWithMugshot(data, file_data)
  1052. In practice, you will usually specify ``request.FILES`` as the source
  1053. of file data (just like you use ``request.POST`` as the source of
  1054. form data)::
  1055. # Bound form with an image field, data from the request
  1056. >>> f = ContactFormWithMugshot(request.POST, request.FILES)
  1057. Constructing an unbound form is the same as always -- omit both form data *and*
  1058. file data::
  1059. # Unbound form with an image field
  1060. >>> f = ContactFormWithMugshot()
  1061. Testing for multipart forms
  1062. ---------------------------
  1063. .. method:: Form.is_multipart()
  1064. If you're writing reusable views or templates, you may not know ahead of time
  1065. whether your form is a multipart form or not. The ``is_multipart()`` method
  1066. tells you whether the form requires multipart encoding for submission::
  1067. >>> f = ContactFormWithMugshot()
  1068. >>> f.is_multipart()
  1069. True
  1070. Here's an example of how you might use this in a template::
  1071. {% if form.is_multipart %}
  1072. <form enctype="multipart/form-data" method="post" action="/foo/">
  1073. {% else %}
  1074. <form method="post" action="/foo/">
  1075. {% endif %}
  1076. {{ form }}
  1077. </form>
  1078. Subclassing forms
  1079. =================
  1080. If you have multiple ``Form`` classes that share fields, you can use
  1081. subclassing to remove redundancy.
  1082. When you subclass a custom ``Form`` class, the resulting subclass will
  1083. include all fields of the parent class(es), followed by the fields you define
  1084. in the subclass.
  1085. In this example, ``ContactFormWithPriority`` contains all the fields from
  1086. ``ContactForm``, plus an additional field, ``priority``. The ``ContactForm``
  1087. fields are ordered first::
  1088. >>> class ContactFormWithPriority(ContactForm):
  1089. ... priority = forms.CharField()
  1090. >>> f = ContactFormWithPriority(auto_id=False)
  1091. >>> print(f.as_ul())
  1092. <li>Subject: <input type="text" name="subject" maxlength="100" required></li>
  1093. <li>Message: <input type="text" name="message" required></li>
  1094. <li>Sender: <input type="email" name="sender" required></li>
  1095. <li>Cc myself: <input type="checkbox" name="cc_myself"></li>
  1096. <li>Priority: <input type="text" name="priority" required></li>
  1097. It's possible to subclass multiple forms, treating forms as mixins. In this
  1098. example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``
  1099. (in that order), and its field list includes the fields from the parent
  1100. classes::
  1101. >>> from django import forms
  1102. >>> class PersonForm(forms.Form):
  1103. ... first_name = forms.CharField()
  1104. ... last_name = forms.CharField()
  1105. >>> class InstrumentForm(forms.Form):
  1106. ... instrument = forms.CharField()
  1107. >>> class BeatleForm(InstrumentForm, PersonForm):
  1108. ... haircut_type = forms.CharField()
  1109. >>> b = BeatleForm(auto_id=False)
  1110. >>> print(b.as_ul())
  1111. <li>First name: <input type="text" name="first_name" required></li>
  1112. <li>Last name: <input type="text" name="last_name" required></li>
  1113. <li>Instrument: <input type="text" name="instrument" required></li>
  1114. <li>Haircut type: <input type="text" name="haircut_type" required></li>
  1115. It's possible to declaratively remove a ``Field`` inherited from a parent class
  1116. by setting the name of the field to ``None`` on the subclass. For example::
  1117. >>> from django import forms
  1118. >>> class ParentForm(forms.Form):
  1119. ... name = forms.CharField()
  1120. ... age = forms.IntegerField()
  1121. >>> class ChildForm(ParentForm):
  1122. ... name = None
  1123. >>> list(ChildForm().fields)
  1124. ['age']
  1125. .. _form-prefix:
  1126. Prefixes for forms
  1127. ==================
  1128. .. attribute:: Form.prefix
  1129. You can put several Django forms inside one ``<form>`` tag. To give each
  1130. ``Form`` its own namespace, use the ``prefix`` keyword argument::
  1131. >>> mother = PersonForm(prefix="mother")
  1132. >>> father = PersonForm(prefix="father")
  1133. >>> print(mother.as_ul())
  1134. <li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" required></li>
  1135. <li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" required></li>
  1136. >>> print(father.as_ul())
  1137. <li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" required></li>
  1138. <li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" required></li>
  1139. The prefix can also be specified on the form class::
  1140. >>> class PersonForm(forms.Form):
  1141. ... ...
  1142. ... prefix = 'person'