【问题标题】:django localtime template filter doesn't workdjango 本地时间模板过滤器不起作用
【发布时间】:2023-03-07 22:29:01
【问题描述】:

我使用 django 1.10 来显示日期时间。日期时间存储在 mongodb 中,它始终是没有时区信息的 UTC,所以我需要根据运行 django 的机器时区显示日期时间。

首先,在settings.py中添加这些

TIME_ZONE = 'Asia/Chongqing'
USE_I18N = True
USE_L10N = True
USE_TZ = True

然后在views.py中添加:

import pytz
from tzlocal import get_localzone
from django.utils import timezone
local_tz = get_localzone()
timezone.activate(local_tz)
# make datetime object and pass it to html to render

在模板.html中:

{% load tz %}
<table border="1">
{% for i in online %}
    <tr>
        <td align='center'>{{ i.time|localtime}}</td>
    </tr>
{% endfor %}
</table>

但日期时间仍然是 UTC,即使我将 tzinfo 添加到传递到 html 的日期时间。

我错过了什么吗?

【问题讨论】:

  • 模板中的“i”是时区感知的日期时间吗?尝试检查该日期时间对象的 tzinfo。

标签: django datetime


【解决方案1】:

为了使本地时间过滤器起作用,您需要包括:

{% load tz %}

https://docs.djangoproject.com/en/2.2/topics/i18n/timezones/#std:templatefilter-localtime

【讨论】:

    猜你喜欢
    • 2016-05-20
    • 2020-03-07
    • 2015-06-18
    • 2011-03-29
    • 2018-05-04
    • 2020-06-19
    • 2014-09-28
    相关资源
    最近更新 更多