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