Reputation: 10786
In my Website I have a timeline view where the user can see all the organized events (upcoming and past), for this I created an Event Model that has a DateTimeField and now I'm trying to group the results to render them in the template. The desired output is:
- 2014
-- January
---- event1
---- event2
-- February
---- event1
---- event2
....
- 2015
-- January
....
My attempt at grouping by year:
events = {}
last_year = None
current_year_events = []
for event in ProofEvent.objects.all().order_by("date"):
year = event.date.year
if year != last_year:
current_year_events.append(event)
events[year] = current_year_events
last_year = year
current_year_events = []
print event.title
else:
current_year_events.append(event)
print event.title
print events
Upvotes: 1
Views: 85
Reputation: 45575
If you trying to group events only for template rendering then it is unnecessary. You can pass a flat list of events and use {% ifchanged %}
template tag:
{% for event in events %}
{% ifchanged %}<h2>{{ event.date|date:"Y" }}</h2>{% endifchanged %}
{% ifchanged %}<h3>{{ event.date|date:"F" }}</h3>{% endifchanged %}
<div>{{ event.title }}</div>
{% endfor %}
Upvotes: 3