django: Group list by date in templates

0 Comments

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.

1.<h2>Drafts</h2>
2. 
3.  <ul class="ulbox">
4. 
5.  {% for draft in drafts %}
6.    <li><a href="#">{{ draft.name }}</a> (created {{ draft.created_on }})</li>
7.  {% endfor %}
8.</ul>

image

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

1.{% 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 %}
2.  <li><b>{{ days.grouper }}</b></li>
3. 
4.  {% for draft in days.list %}
5.    <li><a href="#">{{ draft.name }}</a> (created {{ draft.created_on }})</li>
6.  {% endfor %}
7.{% endfor %}
8.</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