简体   繁体   中英

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 . Instead, the value remains in UTC.

I was able to solve this by creating a filter that runs localtime() on the values.

However, I am not sure how to do the same thing with DateTimeFields . In the template, I have {{ field }} , where field is the DateTimeField , but there is nowhere to put a filter.

What is the best way to convert DateTimeField values to the current timezone?

Thankfully this is a relatively easy fix. Django provides a function named template_localtime that (according to the documentation) does the following:

"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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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