简体   繁体   English

在Jinja2模板中使用DateTimeFields显示本地时间-Django

[英]Displaying local time using DateTimeFields in Jinja2 templates - Django

When using Django and Jinja2, it seems that datetime objects don't get converted to the local timezone automatically, even if USE_TZ=True . 使用Django和Jinja2时,即使USE_TZ=Truedatetime对象也不会自动转换为本地时区。 Instead, the value remains in UTC. 取而代之的是,该值保留在UTC中。

I was able to solve this by creating a filter that runs localtime() on the values. 我能够通过创建一个在值上运行localtime()的过滤器来解决此问题。

However, I am not sure how to do the same thing with DateTimeFields . 但是,我不确定如何使用DateTimeFields进行相同的操作。 In the template, I have {{ field }} , where field is the DateTimeField , but there is nowhere to put a filter. 在模板中,我有{{ field }} ,其中field是DateTimeField ,但是没有地方可以放置过滤器。

What is the best way to convert DateTimeField values to the current timezone? DateTimeField值转换为当前时区的最佳方法是什么?

Thankfully this is a relatively easy fix. 幸运的是,这是一个相对容易的修复。 Django provides a function named template_localtime that (according to the documentation) does the following: Django提供了一个名为template_localtime的函数(根据文档)执行以下操作:

"Checks if value is a datetime and converts it to local time if necessary." “检查值是否为日期时间,并在必要时将其转换为本地时间。”

Exposing this to Jinja2 templates involves either the creation of a template filter or a global function. 将其暴露给Jinja2模板涉及创建模板过滤器或全局函数。 This example demonstrates both: 此示例说明了两个:

from django.utils.timezone import template_localtime

env = Environment(**kwargs)
env.filters.update({
    'localtime': template_localtime,
})
env.globals.update({
    'localtime': template_localtime,
})

You can then use these in a Jinja2 template as follows: 然后,您可以在Jinja2模板中使用它们,如下所示:

{{ item.date|localtime }}
{{ localtime(item.date) }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM