我知道我可以str在 Django 模板中获取当前日期(使用模板标签now),如下所示:
{% now "Y-m-d" as today_str %}
<p>{{ today_str }}</p>
但我不能将其用于比较:
{% now "Y-m-d" as today_str %}
{% for elem in object_list %}
{% if elem.date < today_str %} {# WRONG: this compares 'date' and 'str' #}
<p>{{ elem.pk }} before today</p>
{# do some other rendering #}
{% endif %}
{% endfor %}
可能的解决方案:
我知道我可以将上下文变量传递给模板,但在我看来它需要代码:
# in my class-based-view in 'views.py'
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['today'] = timezone.now()
return ctx
或者我可以创建一个自定义模板标签,但这是更多的附加代码。
正如你所看到的,我有解决我的问题的方法,但我想知道是否有一种内置方式来获取模板中的当前date(或datetime)?
人到中年有点甜
随时随地看视频慕课网APP
相关分类