api.txt 61 KB

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