问题
How do I compare dates in a Django template? I thought of several possible avenues:
- Send today's date in the context to be compared at the template
- Create my own template tag
- Have some logic in the view to only pass the date if it's in the future
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.
回答1:
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"}}
回答2:
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).
来源:https://stackoverflow.com/questions/4493761/django-templates-display-a-date-only-if-its-in-the-future