Django: display text between form fields
Hi Stackoverflow people,
I am displaying a large form through a loop:
<table>
{% for field in projectDetailForm %}
<tr>
<td> {{ field.label_tag }} </td>
<td> {{ field }} </td>
</tr>
{% endfor %}
</table>
I would like to interrupt the table with the form fields after a few form fields to display more explanations. Since the form is fairly large (20 fields开发者_如何学Go), I would like to avoid the "manual display" of each form field (as described here).
Is there a way to display the text form within the loop, either after the x-th loop or after a specific form field?
Thank you for your advice!
I would either use forloop.counter
or set a custom attribute on a form field on form initialization and display the attribute the same way you display field.label_tag
You can add a method to your form, which will return fields by portions. Something like:
def by_5(self):
iterable = iter(self)
zipped = zip(*([iterable] * 5)) # replace 5 by desired n
for z in zipped:
yield z
remained = list(iterable)
if remained:
yield remained
Then in template:
<table>
{% for fields in projectDetailForm.by_5 %}
{% for field in fields %}
<tr>
<td> {{ field.label_tag }} </td>
<td> {{ field }} </td>
</tr>
{% endfor %}
<tr><td colspan="2">Hi there!</td></tr>
{% endfor %}
</table>
There is a {{ forloop.counter }}
and {{ forloop.counter0 }}
(1-indexed and 0-indexed respectively) that you can use.
For a few more information, check this Djangobook link.
精彩评论