How to go through a ManyToMany field in chunks in Django
<p>I am trying to display sets of three objects in a HTML template in a tiled interface. So, for example, an Album model has a ManyToMany field with specific photos. I want to iterate through the photos and show them in sets of three in the view. Currently, I can get all the photos using <code>{{ for photo in album.images.all }}</code> in the template, but don't know how to get the results in sets of three. </p>

<p>How would I go about chunking the results into sets of three so that I can then iterate through the sets of three for the template? Or is there a way to get the total length and then index of specific elements using the Template tags?</p>

<p>Thanks</p>

<pre><code>{% for photo in album.images.all %}
    {{ photo }}
    {% if forloop.counter|divisibleby:4 %}
        &lt;hr&gt; {# or some other markup #}
    {% endif
{% endfor %}
</code></pre>

<p>You might also do the grouping in your view. This might result in cleaner markup. See: <a href="http://stackoverflow.com/questions/11964972/django-template-for-tag-add-li-every-4th-element#answer-11965885">Django template {%for%} tag add li every 4th element</a></p>

python django