django localtime template filter doesn't work

末鹿安然 提交于 2021-02-05 06:43:25

问题


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.

First, add those in settings.py

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

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

in template.html:

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

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

Did I miss something?


回答1:


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



来源:https://stackoverflow.com/questions/39653750/django-localtime-template-filter-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!