When creating a blog-type Web application, I thought about creating a view that can display posts as a list using ListView. I tried to display it using the For statement, but as expected, it was sorted in order from the oldest post, so I want to sort it in the newest order. (I want to change the display method from ascending order to descending order)
I thought about putting a list in the reverse order in a variable and turning it with a For statement, but I wrote it using the simpler for statement reversed.
list.html
{% for i in object_list reversed %}
<div class="post-preview">
<a href="{% url 'post' i.pk %}">
<h2 class="post-title">{{ i.title }}</h2>
<h3 class="post-subtitle">{{ i.subtitle }}</h3>
</a>
</div>
{% endfor %}
By the way
{% for i in reversed(object_list) %}
I also found out how to write it, but I got an error. Maybe it's because there is a unique `{%%}`
when writing Python in HTML.
So for the time being, I think `{% for i in object_list reversed%}`
is correct.
Recommended Posts