简体   繁体   中英

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 . 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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM