1๐
โ
You can use {{forloop.first}}
for this. So your code can be updated to
{% for message in messages %}
{% if message.date - current.date < 24 hours %}
{% if forloop.first %}
TODAY
{% endif %}
{% elif message.date - current.date > 24 hours and message.date - current.date < 48 hours %}
{% if forloop.first %}
YESTERDAY
{% endif %}
{% endif %}
Sent by: {{ message.sender }}
{{ message.body }}
{% endfor %}
๐คRohan
1๐
I am trying to group messages by received today, received yesterday
@Rohan gave you an answer but it will run the check on each loop even though you only print out the string once.
A better approach would be to organize your messages and order them by the date difference.
The best way to do this is to group the messages in the view before sending them to the template, like this:
from collections import defaultdict
from django.utils.timesince import timesince # This will give us nice human
# friendly date offsets
def some_view(request):
messages = Message.objects.order_by('date')
grouped_messaged = defaultdict(list)
for message in messages:
grouped_messages[timesince(message.date)].append(message)
return render(request, 'template.html', {'all_messages': messages})
Now your template is a lot simpler:
<ul>
{% for header,messages in all_messages.items %}
<li>{{ header }}
<ul>
{% for message in messages %}
<li>{{ message.sender }} - {{ message.body }}</li>
{% endfor %}
</ul></li>
{% endfor %}
</ul>
๐คBurhan Khalid
- [Answered ]-Django url pattern issue in python 2.7.6
- [Answered ]-Urlize escaping %23 in href of text
- [Answered ]-Django Rest Framework nested serializer
- [Answered ]-Deploy with Apache2, mod_wgi and django 1.9 on ubuntu server 16.04
Source:stackexchange.com