[英]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".我发现我应该将它们作为时间戳进行比较,但下面的代码给了我“jinja2.exceptions.UndefinedError:‘as_timestamp’未定义”。
{% 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 %}
It is very easy with custom filter https://docs.djangoproject.com/en/4.1/howto/custom-template-tags/使用自定义过滤器非常容易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 %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.