shogun000
shogun000

Reputation: 303

Render lists of posts grouped by date

My site has multiple posts per day. I want to render a list of posts, but I want the posts grouped by date, not just sorted by date, so that each date has its own list of posts.

I send a list of posts to the template, and post.posted_on is the timestamp when the post was created. How do I render the posts grouped by date?

Upvotes: 1

Views: 214

Answers (1)

davidism
davidism

Reputation: 127320

You can use itertools.groupby to group the posts by day. Sort the posts by posted_on in descending order, then use groupby with a key for the day. Iterate over the groups, and iterate over the posts within each group, to build sections with lists of posts.

from itertools import groupby
# sort posts by date descending first
# should be done with database query, but here's how otherwise
posts = sorted(posts, key=lambda: post.posted_on, reverse=True)
by_date = groupby(posts, key=post.posted_on.date)
return render_template('posts.html', by_date=by_date)
{% for date, group in by_date %}<div>
    <p>{{ date.isoformat() }}</p>
    {% for post in group %}<div>
        {{ post.title }}
        ...
    </div>{% endfor %}
</div>{% endfor %}

Upvotes: 1

Related Questions