Path Parakh
Path Parakh

Reputation: 127

How to reverse the list inside django template?

I have a list and I wanted to order by descinding in django-html template, How can I do it ?

This is my template code

{% for unique_date in unique_dates %}
    <th>{{unique_date}}</th>
{% endfor %}

And this is my view file

unique_dates = list({a.date for a in attendances})
unique_dates.sort()

Upvotes: 2

Views: 2262

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477190

You can sort it in reverse with:

unique_dates = sorted({a.date for a in attendances}, reverse=False)
# no extra sort needed

This will thus sort the a.date items in reversed order, so with the largest (latest) one first, and the smallest (earliest) one last.

An alternative is to work with the {% for … in … reversed %} [Django-doc]:

{# rendering in reverse #}
{% for unique_date in unique_dates reversed %}
    <th>{{ unique_date }}</th>
{% endfor %}

Upvotes: 5

Related Questions