如何仅为django管理门户设置默认TZ? [英] How to set a default TZ for django admin portal only?
问题描述
django中的TIME_ZONE设置将在django在模板中呈现时将UTC存储的数据库日期时间自动转换为该时区。我现在将其设置为 UTC,这是默认设置,并且已经在前端使用moment或在视图中手动为用户处理转换。
The TIME_ZONE setting in django will auto-convert UTC stored DB datetime into that timezone when django renders them in templates. I have it set to "UTC" right now, which is the default, and have been handling conversion for the user either in the front-end using moment, or manually in the view.
但我希望在管理门户中的所有日期时间都使用EST,但不要将其作为普通用户的默认日期。是否可以不更改TIME_ZONE?但是同时,我不想在每个AdminModel / Form中手动进行转换。
But I wish to use EST for all datetime in admin portal, but without making this the default for our regular users. Is this possible without changing TIME_ZONE? But at the same time, I don't want to manually convert this in every AdminModel/Form.
推荐答案
一种简单的方法可以是要创建中间件,该将当前时区设置为 EST
表示管理域中的URL。
A simple approach would be to create a middleware that sets the current timezone to EST
for URLs in the admin domain. Something like:
from django.utils.deprecation import MiddlewareMixin # needed since Django 2.0
from django.utils.timezone import activate
class AdminTimezoneMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.path.startswith("/admin"):
activate(pytz.timezone("EST"))
(当然,对这样的URL进行硬编码是 t非常干燥,但是您明白了。)
(Of course, hardcoding the URL like this isn't very DRY, but you get the idea.)
这篇关于如何仅为django管理门户设置默认TZ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!