如何仅为django管理门户设置默认TZ?

时间:2015-02-18 16:37:18

标签: django django-admin

当django在模板中呈现时,django中的TIME_ZONE设置会将UTC存储的DB日期时间自动转换为该时区。我现在将它设置为“UTC”,这是默认设置,并且已经在前端使用时刻或在视图中手动处理用户的转换。

但我希望在管理门户中使用EST用于所有日期时间,但不要将其作为普通用户的默认值。这可能不改变TIME_ZONE吗?但与此同时,我不想在每个AdminModel / Form中手动转换它。

2 个答案:

答案 0 :(得分:3)

一种简单的方法是为管理域中的网址middleware创建sets the current timezoneEST。类似的东西:

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进行硬编码并不是很干,但你明白了。)

答案 1 :(得分:3)

自Kevin回答以来,Django有了一个新的中间件系统。

这应该适用于1.9,1.10,1.11,2.0

import pytz
from django.utils.timezone import activate


class AdminTimezoneMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(self.process_request(request))
        return response

    @staticmethod
    def process_request(request):
        if request.path.startswith("/admin"):
            activate(pytz.timezone("EST"))
        return request