[Answered ]-How to get the "overall" counter of an object in a group in a Django template?

1๐Ÿ‘

โœ…

I think you will need to add the index in your view, Django intentionally restricts the capabilities within its template language to discourage the inclusion of extensive logic directly within templates. I recommend addressing this by following the suggested approach:

# views.py
from django.shortcuts import render

def your_view(request):
    cities = [
        {"name": "Mumbai", "population": "19,000,000", "country": "India"},
        {"name": "Calcutta", "population": "15,000,000", "country": "India"},
        {"name": "New York", "population": "20,000,000", "country": "USA"},
        {"name": "Chicago", "population": "7,000,000", "country": "USA"},
        {"name": "Tokyo", "population": "33,000,000", "country": "Japan"},
    ]

    # Add an index to each city
    for index, city in enumerate(cities, start=1):
        city['index'] = index

    return render(request, 'your_template.html', {'cities': cities})

Then in your template, you can use the index attribute:

{% regroup cities by country as country_list %}

<ul>
    {% for country in country_list %}
        <li>{{ country.grouper }}
        <ul>
            {% for city in country.list %}
                {% with counter=counter|add:1 %}
                 <li>{{ city.index }}: {{ city.name }}: {{ city.population }}</li>
                {% endwith %}
            {% endfor %}
        </ul>
        </li>
    {% endfor %}
</ul>
๐Ÿ‘คTemi

Leave a comment