[Fixed]-Python Django Template: Iterate Through List

28👍

Do you need i to be an index? If not, see if the following code does what you’re after:

<div id="right_pod">
{% for i in c %}
    <div class="user_pod">
        {{ i.0.from_user }}
    </div>
{% endfor %}

15👍

Please read the entire documentation on the template language’s for loops. First of all, that iteration (like in Python) is over objects, not indexes. Secondly, that within any for loop there is a forloop variable with two fields you’ll be interested in:

Variable            Description
forloop.counter     The current iteration of the loop (1-indexed)
forloop.counter0    The current iteration of the loop (0-indexed)

9👍

You should use the slice template filter to achieve what you want:

Iterate over the object (c in this case) like so:

{% for c in objects|slice:":30" %}

This would make sure that you only iterate over the first 30 objects.

Also, you can use the forloop.counter object to keep track of which loop iteration you’re on.

Leave a comment