[Answered ]-How to get queryset value outside of loop in Django template?

0👍

Like @erework said I restructured the data in my view. If you have any better ways, feel free to edit. Below is how I did it:

#views.py
from django.conf import settings
cities = []
for country in settings.COUNTRIES:
    cities.append([country, City.objects.filter(country=country)])


#cities.html
{% for country, city in cities %}
    <div id="{{country}}">
        <p>Choose a city</p>
        <li>{{ city.name }}</li>
    </div>
{% endfor %}

I wanted my cities list to be sorted by country hence I put the data into a list. Also I only had less than 10 countries so I had a list of them in settings file.

2👍

Maybe using the built in {% regroup %} template tag is more elegant.

It would be something along these lines (not tested):

{% regroup cities by country as country_list %}

{% for country in country_list %}
    <div id="{{country.grouper}}">
        <p>Choose a city</p>    
        {% for city in country.list %}
            <li>{{ city.name }}</li>
        {% endfor %}    
    </div>
{% endfor %}

Interestingly, the example in official Django docs also uses cities and countries. Check it out (linked above).

👤frnhr

Leave a comment