1

I have this below scenario as an example

Current scenario

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

What I want

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

How can I achieve that? Thanks

1
  • 2
    looks like you need a list of countries along with the cities inside and then you probably can. Rework your data structure in your view to do something like [{"countryname": [{"name": etc... Commented Feb 26, 2017 at 21:59

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.