[Answered ]-How can I print the 'date received' only one time while using a for loop?

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

Leave a comment