| | 295 | ``field.is_hidden`` |
|---|
| | 296 | This attribute is ``True`` is the form field is a hidden field and |
|---|
| | 297 | ``False`` otherwise. It's not particularly useful as a template |
|---|
| | 298 | variable, but could be useful in conditional tests such as:: |
|---|
| | 299 | |
|---|
| | 300 | {% if field.is_hidden %} |
|---|
| | 301 | {# Do something special #} |
|---|
| | 302 | {% endif %} |
|---|
| | 303 | |
|---|
| | 304 | Looping over hidden and visible fields |
|---|
| | 305 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|---|
| | 306 | |
|---|
| | 307 | If you are manually laying out a form in a template, you will often want to |
|---|
| | 308 | work with any hidden fields in a single loop and then treat the visible fields |
|---|
| | 309 | differently. For example, since hidden fields don't display anything, putting |
|---|
| | 310 | their error messages "next to" the field isn't going to be very clear to the |
|---|
| | 311 | reader. So you need to handle errors for those fields a bit differently. |
|---|
| | 312 | |
|---|
| | 313 | Django provides two methods on a form that allow you to loop over the hidden |
|---|
| | 314 | and visible fields independently: ``hidden_fields()`` and |
|---|
| | 315 | ``visible_fields()``. In a template, you might use these like this (this is a |
|---|
| | 316 | modification of an earlier example):: |
|---|
| | 317 | |
|---|
| | 318 | <form action="/contact/" method="POST"> |
|---|
| | 319 | {% for field in form.visible_fields %} |
|---|
| | 320 | <div class="fieldWrapper"> |
|---|
| | 321 | |
|---|
| | 322 | {# Include the hidden fields in the form #} |
|---|
| | 323 | {% if forloop.first %} |
|---|
| | 324 | {% for hidden in form.hidden_fields %} |
|---|
| | 325 | {{ field }} |
|---|
| | 326 | {% endfor %} |
|---|
| | 327 | {% endif %} |
|---|
| | 328 | |
|---|
| | 329 | {{ field.errors }} |
|---|
| | 330 | {{ field.label_tag }}: {{ field }} |
|---|
| | 331 | </div> |
|---|
| | 332 | {% endfor %} |
|---|
| | 333 | <p><input type="submit" value="Send message" /></p> |
|---|
| | 334 | </form> |
|---|
| | 335 | |
|---|
| | 336 | This example does not handle any errors in the hidden fields. Usually, an |
|---|
| | 337 | error in a hidden field is a sign of form tampering, since normal form |
|---|
| | 338 | interaction won't alter them. However, you could easily insert some error |
|---|
| | 339 | displays for those form errors as well. |
|---|
| | 340 | |
|---|
| | 341 | .. versionadded:: 1.1 |
|---|
| | 342 | The ``hidden_fields`` and ``visible_fields`` methods are new in Django |
|---|
| | 343 | 1.1. |
|---|
| | 344 | |
|---|