api.txt 45 KB

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