2
0

index.txt 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. ==================
  2. Working with forms
  3. ==================
  4. .. currentmodule:: django.forms
  5. .. admonition:: About this document
  6. This document provides an introduction to the basics of web forms and how
  7. they are handled in Django. For a more detailed look at specific areas of
  8. the forms API, see :doc:`/ref/forms/api`, :doc:`/ref/forms/fields`, and
  9. :doc:`/ref/forms/validation`.
  10. Unless you're planning to build websites and applications that do nothing but
  11. publish content, and don't accept input from your visitors, you're going to
  12. need to understand and use forms.
  13. Django provides a range of tools and libraries to help you build forms to
  14. accept input from site visitors, and then process and respond to the input.
  15. HTML forms
  16. ==========
  17. In HTML, a form is a collection of elements inside ``<form>...</form>`` that
  18. allow a visitor to do things like enter text, select options, manipulate
  19. objects or controls, and so on, and then send that information back to the
  20. server.
  21. Some of these form interface elements - text input or checkboxes - are built
  22. into HTML itself. Others are much more complex; an interface that pops up a
  23. date picker or allows you to move a slider or manipulate controls will
  24. typically use JavaScript and CSS as well as HTML form ``<input>`` elements to
  25. achieve these effects.
  26. As well as its ``<input>`` elements, a form must specify two things:
  27. * *where*: the URL to which the data corresponding to the user's input should
  28. be returned
  29. * *how*: the HTTP method the data should be returned by
  30. As an example, the login form for the Django admin contains several
  31. ``<input>`` elements: one of ``type="text"`` for the username, one of
  32. ``type="password"`` for the password, and one of ``type="submit"`` for the
  33. "Log in" button. It also contains some hidden text fields that the user
  34. doesn't see, which Django uses to determine what to do next.
  35. It also tells the browser that the form data should be sent to the URL
  36. specified in the ``<form>``’s ``action`` attribute - ``/admin/`` - and that it
  37. should be sent using the HTTP mechanism specified by the ``method`` attribute -
  38. ``post``.
  39. When the ``<input type="submit" value="Log in">`` element is triggered, the
  40. data is returned to ``/admin/``.
  41. ``GET`` and ``POST``
  42. --------------------
  43. ``GET`` and ``POST`` are the only HTTP methods to use when dealing with forms.
  44. Django's login form is returned using the ``POST`` method, in which the browser
  45. bundles up the form data, encodes it for transmission, sends it to the server,
  46. and then receives back its response.
  47. ``GET``, by contrast, bundles the submitted data into a string, and uses this
  48. to compose a URL. The URL contains the address where the data must be sent, as
  49. well as the data keys and values. You can see this in action if you do a search
  50. in the Django documentation, which will produce a URL of the form
  51. ``https://docs.djangoproject.com/search/?q=forms&release=1``.
  52. ``GET`` and ``POST`` are typically used for different purposes.
  53. Any request that could be used to change the state of the system - for example,
  54. a request that makes changes in the database - should use ``POST``. ``GET``
  55. should be used only for requests that do not affect the state of the system.
  56. ``GET`` would also be unsuitable for a password form, because the password
  57. would appear in the URL, and thus, also in browser history and server logs,
  58. all in plain text. Neither would it be suitable for large quantities of data,
  59. or for binary data, such as an image. A web application that uses ``GET``
  60. requests for admin forms is a security risk: it can be easy for an attacker to
  61. mimic a form's request to gain access to sensitive parts of the system.
  62. ``POST``, coupled with other protections like Django's :doc:`CSRF protection
  63. </ref/csrf/>` offers more control over access.
  64. On the other hand, ``GET`` is suitable for things like a web search form,
  65. because the URLs that represent a ``GET`` request can easily be bookmarked,
  66. shared, or resubmitted.
  67. Django's role in forms
  68. ======================
  69. Handling forms is a complex business. Consider Django's admin, where numerous
  70. items of data of several different types may need to be prepared for display in
  71. a form, rendered as HTML, edited using a convenient interface, returned to the
  72. server, validated and cleaned up, and then saved or passed on for further
  73. processing.
  74. Django's form functionality can simplify and automate vast portions of this
  75. work, and can also do it more securely than most programmers would be able to
  76. do in code they wrote themselves.
  77. Django handles three distinct parts of the work involved in forms:
  78. * preparing and restructuring data to make it ready for rendering
  79. * creating HTML forms for the data
  80. * receiving and processing submitted forms and data from the client
  81. It is *possible* to write code that does all of this manually, but Django can
  82. take care of it all for you.
  83. Forms in Django
  84. ===============
  85. We've described HTML forms briefly, but an HTML ``<form>`` is just one part of
  86. the machinery required.
  87. In the context of a web application, 'form' might refer to that HTML
  88. ``<form>``, or to the Django :class:`Form` that produces it, or to the
  89. structured data returned when it is submitted, or to the end-to-end working
  90. collection of these parts.
  91. The Django :class:`Form` class
  92. ------------------------------
  93. At the heart of this system of components is Django's :class:`Form` class. In
  94. much the same way that a Django model describes the logical structure of an
  95. object, its behavior, and the way its parts are represented to us, a
  96. :class:`Form` class describes a form and determines how it works and appears.
  97. In a similar way that a model class's fields map to database fields, a form
  98. class's fields map to HTML form ``<input>`` elements. (A :class:`ModelForm`
  99. maps a model class's fields to HTML form ``<input>`` elements via a
  100. :class:`Form`; this is what the Django admin is based upon.)
  101. A form's fields are themselves classes; they manage form data and perform
  102. validation when a form is submitted. A :class:`DateField` and a
  103. :class:`FileField` handle very different kinds of data and have to do
  104. different things with it.
  105. A form field is represented to a user in the browser as an HTML "widget" - a
  106. piece of user interface machinery. Each field type has an appropriate default
  107. :doc:`Widget class </ref/forms/widgets/>`, but these can be overridden as
  108. required.
  109. Instantiating, processing, and rendering forms
  110. ----------------------------------------------
  111. When rendering an object in Django, we generally:
  112. #. get hold of it in the view (fetch it from the database, for example)
  113. #. pass it to the template context
  114. #. expand it to HTML markup using template variables
  115. Rendering a form in a template involves nearly the same work as rendering any
  116. other kind of object, but there are some key differences.
  117. In the case of a model instance that contained no data, it would rarely if ever
  118. be useful to do anything with it in a template. On the other hand, it makes
  119. perfect sense to render an unpopulated form - that's what we do when we want
  120. the user to populate it.
  121. So when we handle a model instance in a view, we typically retrieve it from the
  122. database. When we're dealing with a form we typically instantiate it in the
  123. view.
  124. When we instantiate a form, we can opt to leave it empty or prepopulate it, for
  125. example with:
  126. * data from a saved model instance (as in the case of admin forms for editing)
  127. * data that we have collated from other sources
  128. * data received from a previous HTML form submission
  129. The last of these cases is the most interesting, because it's what makes it
  130. possible for users not just to read a website, but to send information back
  131. to it too.
  132. Building a form
  133. ===============
  134. The work that needs to be done
  135. ------------------------------
  136. Suppose you want to create a simple form on your website, in order to obtain
  137. the user's name. You'd need something like this in your template:
  138. .. code-block:: html+django
  139. <form action="/your-name/" method="post">
  140. <label for="your_name">Your name: </label>
  141. <input id="your_name" type="text" name="your_name" value="{{ current_name }}">
  142. <input type="submit" value="OK">
  143. </form>
  144. This tells the browser to return the form data to the URL ``/your-name/``, using
  145. the ``POST`` method. It will display a text field, labeled "Your name:", and a
  146. button marked "OK". If the template context contains a ``current_name``
  147. variable, that will be used to pre-fill the ``your_name`` field.
  148. You'll need a view that renders the template containing the HTML form, and
  149. that can supply the ``current_name`` field as appropriate.
  150. When the form is submitted, the ``POST`` request which is sent to the server
  151. will contain the form data.
  152. Now you'll also need a view corresponding to that ``/your-name/`` URL which will
  153. find the appropriate key/value pairs in the request, and then process them.
  154. This is a very simple form. In practice, a form might contain dozens or
  155. hundreds of fields, many of which might need to be prepopulated, and we might
  156. expect the user to work through the edit-submit cycle several times before
  157. concluding the operation.
  158. We might require some validation to occur in the browser, even before the form
  159. is submitted; we might want to use much more complex fields, that allow the
  160. user to do things like pick dates from a calendar and so on.
  161. At this point it's much easier to get Django to do most of this work for us.
  162. Building a form in Django
  163. -------------------------
  164. The :class:`Form` class
  165. ~~~~~~~~~~~~~~~~~~~~~~~
  166. We already know what we want our HTML form to look like. Our starting point for
  167. it in Django is this:
  168. .. code-block:: python
  169. :caption: ``forms.py``
  170. from django import forms
  171. class NameForm(forms.Form):
  172. your_name = forms.CharField(label="Your name", max_length=100)
  173. This defines a :class:`Form` class with a single field (``your_name``). We've
  174. applied a human-friendly label to the field, which will appear in the
  175. ``<label>`` when it's rendered (although in this case, the :attr:`~Field.label`
  176. we specified is actually the same one that would be generated automatically if
  177. we had omitted it).
  178. The field's maximum allowable length is defined by
  179. :attr:`~CharField.max_length`. This does two things. It puts a
  180. ``maxlength="100"`` on the HTML ``<input>`` (so the browser should prevent the
  181. user from entering more than that number of characters in the first place). It
  182. also means that when Django receives the form back from the browser, it will
  183. validate the length of the data.
  184. A :class:`Form` instance has an :meth:`~Form.is_valid()` method, which runs
  185. validation routines for all its fields. When this method is called, if all
  186. fields contain valid data, it will:
  187. * return ``True``
  188. * place the form's data in its :attr:`~Form.cleaned_data` attribute.
  189. The whole form, when rendered for the first time, will look like:
  190. .. code-block:: html+django
  191. <label for="your_name">Your name: </label>
  192. <input id="your_name" type="text" name="your_name" maxlength="100" required>
  193. Note that it **does not** include the ``<form>`` tags, or a submit button.
  194. We'll have to provide those ourselves in the template.
  195. .. _using-a-form-in-a-view:
  196. The view
  197. ~~~~~~~~
  198. Form data sent back to a Django website is processed by a view, generally the
  199. same view which published the form. This allows us to reuse some of the same
  200. logic.
  201. To handle the form we need to instantiate it in the view for the URL where we
  202. want it to be published:
  203. .. code-block:: python
  204. :caption: ``views.py``
  205. from django.http import HttpResponseRedirect
  206. from django.shortcuts import render
  207. from .forms import NameForm
  208. def get_name(request):
  209. # if this is a POST request we need to process the form data
  210. if request.method == "POST":
  211. # create a form instance and populate it with data from the request:
  212. form = NameForm(request.POST)
  213. # check whether it's valid:
  214. if form.is_valid():
  215. # process the data in form.cleaned_data as required
  216. # ...
  217. # redirect to a new URL:
  218. return HttpResponseRedirect("/thanks/")
  219. # if a GET (or any other method) we'll create a blank form
  220. else:
  221. form = NameForm()
  222. return render(request, "name.html", {"form": form})
  223. If we arrive at this view with a ``GET`` request, it will create an empty form
  224. instance and place it in the template context to be rendered. This is what we
  225. can expect to happen the first time we visit the URL.
  226. If the form is submitted using a ``POST`` request, the view will once again
  227. create a form instance and populate it with data from the request: ``form =
  228. NameForm(request.POST)`` This is called "binding data to the form" (it is now
  229. a *bound* form).
  230. We call the form's ``is_valid()`` method; if it's not ``True``, we go back to
  231. the template with the form. This time the form is no longer empty (*unbound*)
  232. so the HTML form will be populated with the data previously submitted, where it
  233. can be edited and corrected as required.
  234. If ``is_valid()`` is ``True``, we'll now be able to find all the validated form
  235. data in its ``cleaned_data`` attribute. We can use this data to update the
  236. database or do other processing before sending an HTTP redirect to the browser
  237. telling it where to go next.
  238. .. _topics-forms-index-basic-form-template:
  239. The template
  240. ~~~~~~~~~~~~
  241. We don't need to do much in our ``name.html`` template:
  242. .. code-block:: html+django
  243. <form action="/your-name/" method="post">
  244. {% csrf_token %}
  245. {{ form }}
  246. <input type="submit" value="Submit">
  247. </form>
  248. All the form's fields and their attributes will be unpacked into HTML markup
  249. from that ``{{ form }}`` by Django's template language.
  250. .. admonition:: Forms and Cross Site Request Forgery protection
  251. Django ships with an easy-to-use :doc:`protection against Cross Site Request
  252. Forgeries </ref/csrf>`. When submitting a form via ``POST`` with
  253. CSRF protection enabled you must use the :ttag:`csrf_token` template tag
  254. as in the preceding example. However, since CSRF protection is not
  255. directly tied to forms in templates, this tag is omitted from the
  256. following examples in this document.
  257. .. admonition:: HTML5 input types and browser validation
  258. If your form includes a :class:`~django.forms.URLField`, an
  259. :class:`~django.forms.EmailField` or any integer field type, Django will
  260. use the ``url``, ``email`` and ``number`` HTML5 input types. By default,
  261. browsers may apply their own validation on these fields, which may be
  262. stricter than Django's validation. If you would like to disable this
  263. behavior, set the ``novalidate`` attribute on the ``form`` tag, or specify
  264. a different widget on the field, like :class:`TextInput`.
  265. We now have a working web form, described by a Django :class:`Form`, processed
  266. by a view, and rendered as an HTML ``<form>``.
  267. That's all you need to get started, but the forms framework puts a lot more at
  268. your fingertips. Once you understand the basics of the process described above,
  269. you should be prepared to understand other features of the forms system and
  270. ready to learn a bit more about the underlying machinery.
  271. More about Django :class:`Form` classes
  272. =======================================
  273. All form classes are created as subclasses of either :class:`django.forms.Form`
  274. or :class:`django.forms.ModelForm`. You can think of ``ModelForm`` as a
  275. subclass of ``Form``. ``Form`` and ``ModelForm`` actually inherit common
  276. functionality from a (private) ``BaseForm`` class, but this implementation
  277. detail is rarely important.
  278. .. admonition:: Models and Forms
  279. In fact if your form is going to be used to directly add or edit a Django
  280. model, a :doc:`ModelForm </topics/forms/modelforms>` can save you a great
  281. deal of time, effort, and code, because it will build a form, along with the
  282. appropriate fields and their attributes, from a ``Model`` class.
  283. Bound and unbound form instances
  284. --------------------------------
  285. The distinction between :ref:`ref-forms-api-bound-unbound` is important:
  286. * An unbound form has no data associated with it. When rendered to the user,
  287. it will be empty or will contain default values.
  288. * A bound form has submitted data, and hence can be used to tell if that data
  289. is valid. If an invalid bound form is rendered, it can include inline error
  290. messages telling the user what data to correct.
  291. The form's :attr:`~Form.is_bound` attribute will tell you whether a form has
  292. data bound to it or not.
  293. More on fields
  294. --------------
  295. Consider a more useful form than our minimal example above, which we could use
  296. to implement "contact me" functionality on a personal website:
  297. .. code-block:: python
  298. :caption: ``forms.py``
  299. from django import forms
  300. class ContactForm(forms.Form):
  301. subject = forms.CharField(max_length=100)
  302. message = forms.CharField(widget=forms.Textarea)
  303. sender = forms.EmailField()
  304. cc_myself = forms.BooleanField(required=False)
  305. Our earlier form used a single field, ``your_name``, a :class:`CharField`. In
  306. this case, our form has four fields: ``subject``, ``message``, ``sender`` and
  307. ``cc_myself``. :class:`CharField`, :class:`EmailField` and
  308. :class:`BooleanField` are just three of the available field types; a full list
  309. can be found in :doc:`/ref/forms/fields`.
  310. Widgets
  311. ~~~~~~~
  312. Each form field has a corresponding :doc:`Widget class </ref/forms/widgets/>`,
  313. which in turn corresponds to an HTML form widget such as ``<input
  314. type="text">``.
  315. In most cases, the field will have a sensible default widget. For example, by
  316. default, a :class:`CharField` will have a :class:`TextInput` widget, that
  317. produces an ``<input type="text">`` in the HTML. If you needed ``<textarea>``
  318. instead, you'd specify the appropriate widget when defining your form field,
  319. as we have done for the ``message`` field.
  320. Field data
  321. ~~~~~~~~~~
  322. Whatever the data submitted with a form, once it has been successfully
  323. validated by calling ``is_valid()`` (and ``is_valid()`` has returned ``True``),
  324. the validated form data will be in the ``form.cleaned_data`` dictionary. This
  325. data will have been nicely converted into Python types for you.
  326. .. note::
  327. You can still access the unvalidated data directly from ``request.POST`` at
  328. this point, but the validated data is better.
  329. In the contact form example above, ``cc_myself`` will be a boolean value.
  330. Likewise, fields such as :class:`IntegerField` and :class:`FloatField` convert
  331. values to a Python ``int`` and ``float`` respectively.
  332. Here's how the form data could be processed in the view that handles this form:
  333. .. code-block:: python
  334. :caption: ``views.py``
  335. from django.core.mail import send_mail
  336. if form.is_valid():
  337. subject = form.cleaned_data["subject"]
  338. message = form.cleaned_data["message"]
  339. sender = form.cleaned_data["sender"]
  340. cc_myself = form.cleaned_data["cc_myself"]
  341. recipients = ["info@example.com"]
  342. if cc_myself:
  343. recipients.append(sender)
  344. send_mail(subject, message, sender, recipients)
  345. return HttpResponseRedirect("/thanks/")
  346. .. tip::
  347. For more on sending email from Django, see :doc:`/topics/email`.
  348. Some field types need some extra handling. For example, files that are uploaded
  349. using a form need to be handled differently (they can be retrieved from
  350. ``request.FILES``, rather than ``request.POST``). For details of how to handle
  351. file uploads with your form, see :ref:`binding-uploaded-files`.
  352. Working with form templates
  353. ===========================
  354. All you need to do to get your form into a template is to place the form
  355. instance into the template context. So if your form is called ``form`` in the
  356. context, ``{{ form }}`` will render its ``<label>`` and ``<input>`` elements
  357. appropriately.
  358. .. admonition:: Additional form template furniture
  359. Don't forget that a form's output does *not* include the surrounding
  360. ``<form>`` tags, or the form's ``submit`` control. You will have to provide
  361. these yourself.
  362. .. _reusable-form-templates:
  363. Reusable form templates
  364. -----------------------
  365. The HTML output when rendering a form is itself generated via a template. You
  366. can control this by creating an appropriate template file and setting a custom
  367. :setting:`FORM_RENDERER` to use that
  368. :attr:`~django.forms.renderers.BaseRenderer.form_template_name` site-wide. You
  369. can also customize per-form by overriding the form's
  370. :attr:`~django.forms.Form.template_name` attribute to render the form using the
  371. custom template, or by passing the template name directly to
  372. :meth:`.Form.render`.
  373. The example below will result in ``{{ form }}`` being rendered as the output of
  374. the ``form_snippet.html`` template.
  375. In your templates:
  376. .. code-block:: html+django
  377. # In your template:
  378. {{ form }}
  379. # In form_snippet.html:
  380. {% for field in form %}
  381. <div class="fieldWrapper">
  382. {{ field.errors }}
  383. {{ field.label_tag }} {{ field }}
  384. </div>
  385. {% endfor %}
  386. Then you can configure the :setting:`FORM_RENDERER` setting:
  387. .. code-block:: python
  388. :caption: ``settings.py``
  389. from django.forms.renderers import TemplatesSetting
  390. class CustomFormRenderer(TemplatesSetting):
  391. form_template_name = "form_snippet.html"
  392. FORM_RENDERER = "project.settings.CustomFormRenderer"
  393. … or for a single form::
  394. class MyForm(forms.Form):
  395. template_name = "form_snippet.html"
  396. ...
  397. … or for a single render of a form instance, passing in the template name to
  398. the :meth:`.Form.render`. Here's an example of this being used in a view::
  399. def index(request):
  400. form = MyForm()
  401. rendered_form = form.render("form_snippet.html")
  402. context = {"form": rendered_form}
  403. return render(request, "index.html", context)
  404. See :ref:`ref-forms-api-outputting-html` for more details.
  405. .. _reusable-field-group-templates:
  406. Reusable field group templates
  407. ------------------------------
  408. Each field is available as an attribute of the form, using
  409. ``{{ form.name_of_field }}`` in a template. A field has a
  410. :meth:`~django.forms.BoundField.as_field_group` method which renders the
  411. related elements of the field as a group, its label, widget, errors, and help
  412. text.
  413. This allows generic templates to be written that arrange fields elements in the
  414. required layout. For example:
  415. .. code-block:: html+django
  416. {{ form.non_field_errors }}
  417. <div class="fieldWrapper">
  418. {{ form.subject.as_field_group }}
  419. </div>
  420. <div class="fieldWrapper">
  421. {{ form.message.as_field_group }}
  422. </div>
  423. <div class="fieldWrapper">
  424. {{ form.sender.as_field_group }}
  425. </div>
  426. <div class="fieldWrapper">
  427. {{ form.cc_myself.as_field_group }}
  428. </div>
  429. By default Django uses the ``"django/forms/field.html"`` template which is
  430. designed for use with the default ``"django/forms/div.html"`` form style.
  431. The default template can be customized by setting
  432. :attr:`~django.forms.renderers.BaseRenderer.field_template_name` in your
  433. project-level :setting:`FORM_RENDERER`::
  434. from django.forms.renderers import TemplatesSetting
  435. class CustomFormRenderer(TemplatesSetting):
  436. field_template_name = "field_snippet.html"
  437. … or on a single field::
  438. class MyForm(forms.Form):
  439. subject = forms.CharField(template_name="my_custom_template.html")
  440. ...
  441. … or on a per-request basis by calling
  442. :meth:`.BoundField.render` and supplying a template name::
  443. def index(request):
  444. form = ContactForm()
  445. subject = form["subject"]
  446. context = {"subject": subject.render("my_custom_template.html")}
  447. return render(request, "index.html", context)
  448. Rendering fields manually
  449. -------------------------
  450. More fine grained control over field rendering is also possible. Likely this
  451. will be in a custom field template, to allow the template to be written once
  452. and reused for each field. However, it can also be directly accessed from the
  453. field attribute on the form. For example:
  454. .. code-block:: html+django
  455. {{ form.non_field_errors }}
  456. <div class="fieldWrapper">
  457. {{ form.subject.errors }}
  458. <label for="{{ form.subject.id_for_label }}">Email subject:</label>
  459. {{ form.subject }}
  460. </div>
  461. <div class="fieldWrapper">
  462. {{ form.message.errors }}
  463. <label for="{{ form.message.id_for_label }}">Your message:</label>
  464. {{ form.message }}
  465. </div>
  466. <div class="fieldWrapper">
  467. {{ form.sender.errors }}
  468. <label for="{{ form.sender.id_for_label }}">Your email address:</label>
  469. {{ form.sender }}
  470. </div>
  471. <div class="fieldWrapper">
  472. {{ form.cc_myself.errors }}
  473. <label for="{{ form.cc_myself.id_for_label }}">CC yourself?</label>
  474. {{ form.cc_myself }}
  475. </div>
  476. Complete ``<label>`` elements can also be generated using the
  477. :meth:`~django.forms.BoundField.label_tag`. For example:
  478. .. code-block:: html+django
  479. <div class="fieldWrapper">
  480. {{ form.subject.errors }}
  481. {{ form.subject.label_tag }}
  482. {{ form.subject }}
  483. </div>
  484. Rendering form error messages
  485. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  486. The price of this flexibility is a bit more work. Until now we haven't had to
  487. worry about how to display form errors, because that's taken care of for us. In
  488. this example we have had to make sure we take care of any errors for each field
  489. and any errors for the form as a whole. Note ``{{ form.non_field_errors }}`` at
  490. the top of the form and the template lookup for errors on each field.
  491. Using ``{{ form.name_of_field.errors }}`` displays a list of form errors,
  492. rendered as an unordered list. This might look like:
  493. .. code-block:: html+django
  494. <ul class="errorlist">
  495. <li>Sender is required.</li>
  496. </ul>
  497. The list has a CSS class of ``errorlist`` to allow you to style its appearance.
  498. If you wish to further customize the display of errors you can do so by looping
  499. over them:
  500. .. code-block:: html+django
  501. {% if form.subject.errors %}
  502. <ol>
  503. {% for error in form.subject.errors %}
  504. <li><strong>{{ error|escape }}</strong></li>
  505. {% endfor %}
  506. </ol>
  507. {% endif %}
  508. Non-field errors (and/or hidden field errors that are rendered at the top of
  509. the form when using helpers like ``form.as_p()``) will be rendered with an
  510. additional class of ``nonfield`` to help distinguish them from field-specific
  511. errors. For example, ``{{ form.non_field_errors }}`` would look like:
  512. .. code-block:: html+django
  513. <ul class="errorlist nonfield">
  514. <li>Generic validation error</li>
  515. </ul>
  516. See :doc:`/ref/forms/api` for more on errors, styling, and working with form
  517. attributes in templates.
  518. Looping over the form's fields
  519. ------------------------------
  520. If you're using the same HTML for each of your form fields, you can reduce
  521. duplicate code by looping through each field in turn using a ``{% for %}``
  522. loop:
  523. .. code-block:: html+django
  524. {% for field in form %}
  525. <div class="fieldWrapper">
  526. {{ field.errors }}
  527. {{ field.label_tag }} {{ field }}
  528. {% if field.help_text %}
  529. <p class="help" id="{{ field.auto_id }}_helptext">
  530. {{ field.help_text|safe }}
  531. </p>
  532. {% endif %}
  533. </div>
  534. {% endfor %}
  535. Useful attributes on ``{{ field }}`` include:
  536. ``{{ field.errors }}``
  537. Outputs a ``<ul class="errorlist">`` containing any validation errors
  538. corresponding to this field. You can customize the presentation of
  539. the errors with a ``{% for error in field.errors %}`` loop. In this
  540. case, each object in the loop is a string containing the error message.
  541. ``{{ field.field }}``
  542. The :class:`~django.forms.Field` instance from the form class that
  543. this :class:`~django.forms.BoundField` wraps. You can use it to access
  544. :class:`~django.forms.Field` attributes, e.g.
  545. ``{{ char_field.field.max_length }}``.
  546. ``{{ field.help_text }}``
  547. Any help text that has been associated with the field.
  548. ``{{ field.html_name }}``
  549. The name of the field that will be used in the input element's name
  550. field. This takes the form prefix into account, if it has been set.
  551. ``{{ field.id_for_label }}``
  552. The ID that will be used for this field (``id_email`` in the example
  553. above). If you are constructing the label manually, you may want to use
  554. this in lieu of ``label_tag``. It's also useful, for example, if you have
  555. some inline JavaScript and want to avoid hardcoding the field's ID.
  556. ``{{ field.is_hidden }}``
  557. This attribute is ``True`` if the form field is a hidden field and
  558. ``False`` otherwise. It's not particularly useful as a template
  559. variable, but could be useful in conditional tests such as:
  560. .. code-block:: html+django
  561. {% if field.is_hidden %}
  562. {# Do something special #}
  563. {% endif %}
  564. ``{{ field.label }}``
  565. The label of the field, e.g. ``Email address``.
  566. ``{{ field.label_tag }}``
  567. The field's label wrapped in the appropriate HTML ``<label>`` tag. This
  568. includes the form's :attr:`~django.forms.Form.label_suffix`. For example,
  569. the default ``label_suffix`` is a colon:
  570. .. code-block:: html+django
  571. <label for="id_email">Email address:</label>
  572. ``{{ field.legend_tag }}``
  573. Similar to ``field.label_tag`` but uses a ``<legend>`` tag in place of
  574. ``<label>``, for widgets with multiple inputs wrapped in a ``<fieldset>``.
  575. ``{{ field.use_fieldset }}``
  576. This attribute is ``True`` if the form field's widget contains multiple
  577. inputs that should be semantically grouped in a ``<fieldset>`` with a
  578. ``<legend>`` to improve accessibility. An example use in a template:
  579. .. code-block:: html+django
  580. {% if field.use_fieldset %}
  581. <fieldset>
  582. {% if field.label %}{{ field.legend_tag }}{% endif %}
  583. {% else %}
  584. {% if field.label %}{{ field.label_tag }}{% endif %}
  585. {% endif %}
  586. {{ field }}
  587. {% if field.use_fieldset %}</fieldset>{% endif %}
  588. ``{{ field.value }}``
  589. The value of the field. e.g ``someone@example.com``.
  590. .. seealso::
  591. For a complete list of attributes and methods, see
  592. :class:`~django.forms.BoundField`.
  593. Looping over hidden and visible fields
  594. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  595. If you're manually laying out a form in a template, as opposed to relying on
  596. Django's default form layout, you might want to treat ``<input type="hidden">``
  597. fields differently from non-hidden fields. For example, because hidden fields
  598. don't display anything, putting error messages "next to" the field could cause
  599. confusion for your users -- so errors for those fields should be handled
  600. differently.
  601. Django provides two methods on a form that allow you to loop over the hidden
  602. and visible fields independently: ``hidden_fields()`` and
  603. ``visible_fields()``. Here's a modification of an earlier example that uses
  604. these two methods:
  605. .. code-block:: html+django
  606. {# Include the hidden fields #}
  607. {% for hidden in form.hidden_fields %}
  608. {{ hidden }}
  609. {% endfor %}
  610. {# Include the visible fields #}
  611. {% for field in form.visible_fields %}
  612. <div class="fieldWrapper">
  613. {{ field.errors }}
  614. {{ field.label_tag }} {{ field }}
  615. </div>
  616. {% endfor %}
  617. This example does not handle any errors in the hidden fields. Usually, an
  618. error in a hidden field is a sign of form tampering, since normal form
  619. interaction won't alter them. However, you could easily insert some error
  620. displays for those form errors, as well.
  621. Further topics
  622. ==============
  623. This covers the basics, but forms can do a whole lot more:
  624. .. toctree::
  625. :maxdepth: 2
  626. formsets
  627. modelforms
  628. media
  629. .. seealso::
  630. :doc:`The Forms Reference </ref/forms/index>`
  631. Covers the full API reference, including form fields, form widgets,
  632. and form and field validation.