Search code examples
jinja2

How to check whether the date is in the future?


I need to display the information if the date given is in the future. Is there a way to do this in a template?

I found out I should compare them as timestamps but the following code gives me "jinja2.exceptions.UndefinedError: 'as_timestamp' is undefined".

{% if as_timestamp(bibjson.discontinued_date) <=  as_timestamp(time.today) %}
  <p>This date should be displayed only if in the past: {{ date.strftime("%d %B %Y") }}</p>
{% endif %}


Solution

  • It is very easy with custom filter https://docs.djangoproject.com/en/4.1/howto/custom-template-tags/

    The filter file:

    import datetime
    
    from django.template import Library
    
    register = Library()
    
    
    @register.filter('date_in_the_past')
    def date_in_the_past(date):
        now = datetime.datetime.now()
        return date <= now
    

    and in the template:

    {% load filter %}
    {% if bibjson.discontinued_date|date_in_the_past %}
        <p>This date should be displayed only if in the past: {{ bibjson.discontinued_date|date:'d F Y' }}</p>
    {% endif %}