Django模板:仅在将来显示日期 [英] Django Templates: Display a date only if it's in the future

查看:139
本文介绍了Django模板:仅在将来显示日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何比较Django模板中的日期?我想到了几个可能的途径:

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.

推荐答案

我会用模板过滤器:

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"}}

这篇关于Django模板:仅在将来显示日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆