如何在Django中执行嵌套循环

如何在Django中执行嵌套循环,django,django-templates,Django,Django Templates,我试图循环我的choicefield表单,并在中环绕每4个,这样每行只有4个选项。问题是我似乎无法理解django中的嵌套循环。关于父循环的文档几乎什么都没有,我也尝试过创建一个模板标记计数器,但没有效果 以下是我的工作内容: {{ counter.count }} {% for check in form.pt_medical_condition %} {% if counter.count == 4 %} <div>

我试图循环我的choicefield表单,并在
中环绕每4个,这样每行只有4个选项。问题是我似乎无法理解django中的嵌套循环。关于父循环的文档几乎什么都没有,我也尝试过创建一个模板标记计数器,但没有效果

以下是我的工作内容:

    {{ counter.count }}
    {% for check in form.pt_medical_condition %}
        
{% if counter.count == 4 %}
        <div>
        {% endif %}

    <label>
    {{ check.tag }} {{ check.choice_label }}
    </label>

        {% if counter.count == 4 %}
        </div>
        {% endif %}

{% if counter.count == 4 %}
{{ counter.count = 0 }}
{% endif %}
    {{ counter.increment }}
    {% endfor %}
{{counter.count}
{%用于签入表单.pt\u医疗条件%}
{%if counter.count==4%}
{%endif%}
{{check.tag}{{check.choice_label}
{%if counter.count==4%}
{%endif%}
{%if counter.count==4%}
{{counter.count=0}}
{%endif%}
{{counter.increment}}
{%endfor%}

有没有一种更简单的方法可以在没有模板标记的情况下实现这一点,因为我的模板标记根本不起作用?谢谢

您可以尝试的一件事是使用
{{{forloop.counter}}
自动递增,这样您就不必手动执行该部分。此外,您还可以测试forloop.counter | divisibleby:4,而不是尝试每隔4个增量重置计数器

比如说:

{% for check in form.pt_medical_condition %}    
    {% if forloop.counter|divisibleby:4 %}
        <div>
    {% endif %}

    <label>
        {{ check.tag }} {{ check.choice_label }}
    </label>

    {% if forloop.counter|divisibleby:4 %}
        </div>
    {% endif %}
{% endfor %}
{%for check-in form.pt\u medical\u condition%}
{%if-forloop.counter | divisibleby:4%}
{%endif%}
{{check.tag}{{check.choice_label}
{%if-forloop.counter | divisibleby:4%}
{%endif%}
{%endfor%}