How can I print the “received date” only once when using the for loop?

I am trying to group messages received today, received yesterday, ect. To clarify, I'm trying to create a single headline that says “Today,” and then list these posts below. I am NOT trying to print “Today” with every message that was received that day (what is currently happening).

I currently have the TODAY and YESTERDAY headers inside the for loop, so I understand why it prints these headers for each mail message, but as said before, I just want to print them once. My question is: how can I achieve this using the following code? Do I need to do separate loops for each time period (today, yesterday, last week, ect.), Or is there a more efficient way to do this?

{% for message in messages %}
    {% if message.date - current.date < 24 hours %}
        TODAY
        Sent by: {{ message.sender }}
        {{ message.body }}
    {% elif message.date - current.date > 24 hours and message.date - current.date < 48 hours %}
        YESTERDAY
        Sent by: {{ message.sender }}
        {{ message.body }
    {% endif %}
{% endfor %}
+1
source share
2 answers

You can use {{forloop.first}}for this. This way 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 %}
+1
source

I am trying to group messages received today, received yesterday

@Rohan , , .

.

- , :

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})

:

<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>
+1

All Articles