如何在Django中设置不同的时区 [英] How to set different Time zones in Django

查看:79
本文介绍了如何在Django中设置不同的时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个酒店管理系统,在此系统中,对于不同的酒店(子域),需要不同的时区。我该怎么做?

Hi I Have a Hotel Management system, in this for different hotels(Subdomains) different Time zones are required. how can i do this?

推荐答案

有一个非常不错的有关时区的Django文档。您需要确定要说的每个子域的时区是什么意思。通常,Django TIME_ZONE 设置用于指定默认时区。但是,根据您的情况,您实际上需要一个不同的默认 TIME_ZONE 设置,具体取决于正在访问的子域。

There's very nice Django documentation regarding timezones. You'll need to determine exactly what you mean when you say you'd like a different time zone per subdomain. Normally, the Django TIME_ZONE setting is used to specify a default time zone. In your case however, you effectively want a different default TIME_ZONE setting depending on which subdomain is being accessed.

可能实现此目标的最可靠方法是:

Probably the most robust way to achieve this goal is:


  • 始终将日期存储在UTC中,而与分配给子域的时区无关。

  • 编写一些自定义Django中间件,它将设置每个请求到达时使用的默认时区。上面链接的Django文档提供了一个示例。例如:

import django.utils.timezone
from pytz import timezone

class TimezoneMiddleware(object):
    def process_request(self, request):
        # Put logic here to choose timezone based on domain.
        if request.META['HTTP_HOST'] == 'hotel1.subdomain.com':
            tz = timezone('US/Eastern')
        else:
            tz = timezone('UTC')

        if tz:
            django.utils.timezone.activate(tz)
        else:
            django.utils.timezone.deactivate()

现在,当Django处理输入或显示的日期时,它将使用中间件选择的时区。这不能解决使用户处于与设置时区的子域不同时区的问题。通常,可以通过让每个Django用户存储自己的首选时区来解决此问题,并且中间件将根据其会话数据选择时区,如文档中所述。

Now, when Django handles date entered or displayed, it will use the timezone selected by middleware. This doesn't solve the problem of having users in a different time zone to the subdomain for which the time zone is set. Normally, this problem would be solved by having each Django user store their preferred time zone, and the middleware would choose the time zone based on their session data as described in the documentation.

这篇关于如何在Django中设置不同的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆