Skip to content Skip to sidebar Skip to footer

How To Shuffle/randomize List Items After Regrouping Them Using Django's Regroup Template Tag

I have this list presented in dictionaries: cities = [ {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'}, {'name': 'Calcutta', 'population': '15,000,000',

Solution 1:

>>> 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'},
 ]
>>> import random
>>> random.shuffle(cities)
>>> print(cities)
[{'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
{'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'}, 
{'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
{'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'}, 
{'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'}]

So, before rendering data into template shuffle list there.

import randomrandom.shuffle(cities)

Don't use the code of the upper part.

But it will change your country's order. So you can use custom template tag for shuffle.

Firstly create a folder named templatetags. then create a file name __init__.py. it would be empty. and create another file named shuffle.py. there save the bellow code.

# YourApp/templatetags/shuffle.pyimport random
from django import template
register = template.Library()

@register.filterdefshuffle(arg):
    tmp = list(arg)[:]
    random.shuffle(tmp)
    return tmp

Project Directory:

-Your_App--templatetags---__init__.py---shuffle.py

Now in your template:

{% regroup cities by country as country_list %}

<ul>
{% for country in country_list %}
    <li>{{ country.grouper }}
    <ul>
        {% for city in country.list|shuffle %}
          <li>{{ city.name }}: {{ city.population }}</li>
        {% endfor %}
    </ul></li>
{% endfor %}
</ul>

Post a Comment for "How To Shuffle/randomize List Items After Regrouping Them Using Django's Regroup Template Tag"