Django的本地时间模板过滤器不起作用 [英] django localtime template filter doesn't work

查看:42
本文介绍了Django的本地时间模板过滤器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django 1.10来显示日期时间.datetime存储在mongodb中,它始终是UTC,没有时区信息,因此我需要根据运行django的计算机时区来显示日期时间.

I am use django 1.10 to display datetime. The datetime is stored in mongodb and it is always UTC without timezone info, so I need to display the date time according to machine's time zone which run django.

首先,将它们添加到settings.py

First, add those in settings.py

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

然后在views.py中添加:

Then in views.py adds:

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

在template.html中:

in template.html:

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

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

But the datetime still UTC, even I add tzinfo to the datetime which pass into html.

我错过了什么吗?

推荐答案

为使本地时间过滤器正常工作,您需要添加以下内容:

In order for the localtime filter to work, you need to include:

{% load tz %}

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

这篇关于Django的本地时间模板过滤器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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