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

点点圈 提交于 2019-12-06 12:21:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!