api.txt 52 KB

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