相关疑难解决方法(0)

Django 模板 - 是否有内置方法可以将当前日期作为“日期”类型而不是“str”类型获取?

我知道我可以str在 Django 模板中获取当前日期(使用模板标签now),如下所示:

{% now "Y-m-d" as today_str %}
<p>{{ today_str }}</p>
Run Code Online (Sandbox Code Playgroud)

但我不能将其用于比较:

{% 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 %}
Run Code Online (Sandbox Code Playgroud)

可能的解决方案:

  1. 我知道我可以将上下文变量传递给模板,但在我看来它需要代码:

    # 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 …
    Run Code Online (Sandbox Code Playgroud)

python django django-templates

3
推荐指数
1
解决办法
3905
查看次数

标签 统计

django ×1

django-templates ×1

python ×1