何时应该在Django(1.4)中激活/停用当前时区? [英] When should I activate/deactivate the current timezone in Django (1.4)?

查看:143
本文介绍了何时应该在Django(1.4)中激活/停用当前时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以Django 1.4刚刚发布了时区支持,但我对如何以及何时使用文档不断提及的当前时区感到困惑。我应该何时激活和停用用户的当前时区?

So Django 1.4 just was released with time zone support, but I'm confused with how and when to utilize the "current time zone" that the docs keep mentioning. When should I activate and deactivate the current time zone for a user?

我刚刚使用Django,所以我甚至不确定当前的上下文时区将适用于特定用户或Web服务器(跨越所有用户)。对于这一点,任何澄清将是非常好的。

I'm pretty new with Django, so I'm not even sure if the context of the current time zone would apply to a specific user or to the web server (spanning all users). Any clarification on this would be great.

推荐答案

Django 1.4中的新功能使得您的django模板中的用户本地时间/有点简单。

New functionality in Django 1.4 makes rendering user's local time/date in your django templates at bit easier.

首先,您需要设置 TIME_ZONE / USE_TZ 参数。

First of all, you'd need to set up your TIME_ZONE/USE_TZ parameters.

然后,为了使用当前时间区域功能,您需要知道用户的时区。最可靠的方法可能是直接询问用户,并将该信息保存在用户个人资料/会话中。此外,您可以尝试使用 getTimezoneOffset()函数通过javascript设置时区Cookie根据位置做一些地理魔法和图形时区。

Then, in order to use "current time zone" functionality you need to know user's timezone. Probably the most reliable way would be to ask the user directly and save this information in user profile/session. Also, you can try setting timezone cookie via javascript by utilizing getTimezoneOffset() function or try to do some geoip magic and figure timezone by location.

一旦你知道用户的时区值,你可以在你的中间件中激活它:

Once you know user's timezone value, you can activate it in your middleware:

class MyTimezoneMiddleware(object):
    def process_request(self, request):
        user_timezone = request.session.get('current_timezone')

        if user_timezone:
             timezone.activate(user_timezone)
        else:
             timezone.deactivate()

这篇关于何时应该在Django(1.4)中激活/停用当前时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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