How to Compare Dates in Django Templates

How to compare dates in Django templates

Compare date in the view, and pass something like in_the_past (boolean) to the extra_context.

Or better add it to the model as a property.

from datetime import date

@property
def is_past_due(self):
return date.today() > self.date

Then in the template:

{% if listing.is_past_due %}
In the past
{% else %}
{{ listing.date|date:"d M Y" }}
{% endif %}

Basically the template is not the place for date comparison IMO.

DateTime compare in django template

today =  datetime.now()

{% if x.for_meeting.date_created.date < today.date and x.for_meeting.date_created.time < today.time %}

Django - Comparing datetime values in template

You shouldn't have nested braces around variables in an if tag, wether they have a filter or not

{% if date.start|date:'D d M Y' == date.end|date:'D d M Y' %}

How to compare datetime in django template

timesince is a simple wrapper around django.utils.timesince function. The easiest solution for your problem would be to write a custom filter:

from datetime import datetime, timedelta
from django import template
from django.utils.timesince import timesince

register = template.Library()

@register.filter
def timesince_threshold(value, days=7):
"""
return timesince(<value>) if value is more than <days> old. Return value otherwise
"""

if datetime.now() - value < timedelta(days=days):
return timesince(value)
else:
return value
timesince_threshold.is_safe = False


Related Topics



Leave a reply



Submit