How to determine "if time is less than x" inside a django template?

I am currently working on a mailbox using Django-Messages. Right now, when I go to the Inbox, he lists all the messages, but what I'm trying to do is organize the messages in blocks on the page, for today, yesterday, last week, etc. I currently have a for loop that iterates through all the messages and displays them. I would suggest that I need to nest an if statement inside a for loop, maybe like this:

Inbox | Received Today
{% if message.date - current.date < 24 hours %}
   Sent by: {{ message.sender }}
   {{ message.body }}
{% elif message.date - current.date > 24 hours and message.date - current.date < 48 hours %}
   Sent by: {{ message.sender }}
   {{ message.body }

{% endif %}

My question is what I set for "current.date"? I know that I can find the current date in python by doing:

datetime.datetime.now()

but how can i get this in a template? Do I need to do this first in the views, and then use the variable inside the template?

, , , ?

+4
1

.

templatetags, messages_tags.py ( )

messages_tags.py :

# Use datetime if not localizing timezones
import datetime
# Otherwise use timezone
from django.utils import timezone 

from django import template

register = template.Library()

@register.filter
def hours_ago(time, hours):
    return time + datetime.timedelta(hours=hours) < datetime.datetime.now() # or timezone.now() if your time is offset-aware

:

{% load messages_tags %}

Inbox | Received Today
{% if message.date|hours_ago:24 %}
   Sent by: {{ message.sender }}
   {{ message.body }}
{% elif message.date|hours_ago:48 %}
   Sent by: {{ message.sender }}
   {{ message.body }

{% endif %}

django .

., elif, message.date 24 , 24 , if , elif.

, datetime, , . , .

+3

All Articles