[Solved]-When should I activate/deactivate the current timezone in Django (1.4)?

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

Leave a comment