Debian Codegraph @

docs/topics/forms/index.txt

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