簡體   English   中英

如何在Django模板中的表單中獲取字段的長度,大小或數量?

[英]How to I get the length or size or number of fields in a form in a django template?

我想編寫一個這樣的循環,以便可以將表格字段散布在表格中。

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

這不起作用,但是因為上面的代碼在form|length上失敗。 為了使其正常工作,我需要在模板中獲取表單中字段的數量。 有誰知道如何做到這一點? 我到處搜尋,但找不到任何東西。 以下內容不起作用:

form.len
form.length
form|length

謝謝!

我真的不確定您要尋找什么,但聽起來像這樣:

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

我不喜歡此代碼,但這是我的第一個想法。

{% for field in form %}

    {% if forloop.last %}
        {{ forloop.counter }}
    {% endif %}

{% enfor %}

我相信form.fields。

{% for field_name in form.fields %}

感謝您的建議-他們提供了幫助! 這終於對我有用:

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM