Belmin Fernandez
Belmin Fernandez

Reputation: 8647

Django Templates: Display a date only if it's in the future

How do I compare dates in a Django template? I thought of several possible avenues:

Although the last option seems easier, I rather leave the display logic in the template than in the view. I also do not want to pass something that seems so trivial like today's date in the template context.

Perhaps someone has another option or could share their implementation of one of the options I mentioned above and why they decided to go that route.

Upvotes: 1

Views: 4057

Answers (2)

Tommy
Tommy

Reputation: 1239

IMO it is cleaner to do that kind of things in a view or in a helper module, and pass it in the context. The templates are better left with no logic or the very least possible (that's the MVC pattern after all).

Upvotes: 2

Steve Jalim
Steve Jalim

Reputation: 12195

I'd go with a template filter:

from datetime import date
...
@register.filter
def future_dates_only(the_date):
   if the_date > date.today():
       return the_date
   else:
       return None

Then in your view do something like:

{{specialdate|future_dates_only|date:"d M Y"}}

Upvotes: 7

Related Questions