api.txt 61 KB

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