When should I activate/deactivate the current timezone in Django (1.4)?

后端 未结 1 867
青春惊慌失措
青春惊慌失措 2021-02-14 02:19

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 act

1条回答
  •  北海茫月
    2021-02-14 02:34

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

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

    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()
    

    0 讨论(0)
提交回复
热议问题