11

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?

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.

fangsterr
  • 3,670
  • 4
  • 37
  • 54

1 Answers1

12

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()
azalea
  • 11,402
  • 3
  • 35
  • 46
BluesRockAddict
  • 15,525
  • 3
  • 37
  • 35
  • 7
    be sure to also have an else-clause deactivating the timezone. Otherwise the last activated timezone will be used for all consecutive requests until another timezone gets activated. – Bouke Jul 01 '13 at 08:05
  • Very good point since the behaviours is not the same in development / production. – François Constant Jun 20 '15 at 08:26