[英]How to I get the length or size or number of fields in a form in a django template?
I would like to write a loop like this, so that I can spread the form fields out in a table. 我想编写一个这样的循环,以便可以将表格字段散布在表格中。 :
:
{% load widget_tweaks %}
{% load mathfilters %}
{% load get_range %}
{% for k in form|length|div:5|floatformat|add:1|get_range %}
<tr>
{% for field in form %}
{% if forloop.counter >= k|mul:5 and forloop.counter <= k|mul:5|add:4 %}
<th>{{ field.label_tag }}{{ field.errors }}</th>
{% endif %}
{% endfor %}
</tr>
<tr>
{% for field in form %}
{% if forloop.counter >= k|mul:5 and forloop.counter <= k|mul:5|add:4 %}
<td>{{ field|add_class:"span4" }}</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
This doesn't work, but because the code above fails on form|length
. 这不起作用,但是因为上面的代码在
form|length
上失败。 In order for this to work, I need to get, in a template, the number of fields in a form. 为了使其正常工作,我需要在模板中获取表单中字段的数量。 Does anyone know how to do this?
有谁知道如何做到这一点? I've searched all over but can't find anything.
我到处搜寻,但找不到任何东西。 The following do NOT work:
以下内容不起作用:
form.len
form.length
form|length
Thanks! 谢谢!
I'm really not sure what you are looking for, but it sounds like this: 我真的不确定您要寻找什么,但听起来像这样:
{% for field in form %}
<tr>
{% if forloop.counter0|divisibleby:5 %}
<th class="span4">{{ field.label_tag }}{{ field.errors }}</th>
{% else %}
<th>{{ field.label_tag }}{{ field.errors }}</th>
{% endif %}
</tr>
{% endfor%}
{% for field in form %}
<tr>
{% if forloop.counter0|divisibleby:5 %}
<td>{{ field|add_class:"span4" }}</td>
{% else %}
<td>{{ field }}</td>
</tr>
{% endfor %}
I dont like this code, but it was my first idea. 我不喜欢此代码,但这是我的第一个想法。
{% for field in form %}
{% if forloop.last %}
{{ forloop.counter }}
{% endif %}
{% enfor %}
我相信form.fields。
{% for field_name in form.fields %}
thanks for your suggestions - they helped! 感谢您的建议-他们提供了帮助! Here is what finally worked for me:
这终于对我有用:
{% for field in form %}
{% if forloop.counter0|divisibleby:5 %}
<tr>
{% for field in form %}
{% if forloop.counter0 >= forloop.parentloop.counter0 and forloop.counter0 <= forloop.parentloop.counter0|add:4 %}
<th>{{ field.label_tag }}{{ field.errors }} </th>
{% endif %}
{% endfor %}
</tr>
<tr>
{% for field in form %}
{% if forloop.counter0 >= forloop.parentloop.counter0 and forloop.counter0 <= forloop.parentloop.counter0|add:4 %}
<td>{{ field }}</td>
{% endif %}
{% endfor %}
</tr>
{% endif %}
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.