Austin
Austin

Reputation: 103

How to do a nested loop in Django

I'm trying to loop through my choicefield form and surround every 4 in a <div> </div> so that there are only 4 of the choices per line. The problem is I can't seem to figure out nested loops in django. The documentation on parent-loops is almost nothing and I've also tried creating a template tag counter to no avail.

Here's what I'm working with:

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

Is there a simpler way to do this without template tags seeing as mine don't work anyway? Thanks!

Upvotes: 0

Views: 281

Answers (1)

NS0
NS0

Reputation: 6096

One thing you can try is to use {{forloop.counter}} which automatically increments so you don't have to try to do that part manually. Also you can test for forloop.counter|divisibleby:4 instead of trying to reset the counter every 4 increments.

So, something like:

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

Upvotes: 1

Related Questions