api.txt 53 KB

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