django: Group list by date in templates

It is often useful to regroup large lists of data by a date upon displaying.

You can either do this manually in the view, or use a nifty little template tag called "regroup".

First the normal list, which shows you everything "as is" without grouping.

<h2>Drafts</h2><br/>
<ul class="ulbox">

{% for draft in drafts %}
<li><a href="#">{{ draft.name }}</a> (created {{ draft.created_on }})</li>
{% endfor %}
</ul>

image

Now the regrouped template code will be a little trickier, but much more helpful when you're looking at the output.

{% regroup drafts by created_on|date:"d-m-Y" as drafts_by_day %} <h2>Drafts</h2> <ul class="ulbox"> {% for days in drafts_by_day %}
<li><b>{{ days.grouper }}</b></li>

{% for draft in days.list %}
<li><a href="#">{{ draft.name }}</a> (created {{ draft.created_on }})</li>
{% endfor %}
{% endfor %}
</ul>

image

As you can see, this makes it a lot easier for your eyes to find data while skimming the list.

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog