django 1.4 how to automatically get user's timezone from client

23,833

Solution 1

From the documentation:

Selecting the current time zone

The current time zone is the equivalent of the current locale for translations. However, there's no equivalent of the Accept-Language HTTP header that Django could use to determine the user's time zone automatically. Instead, Django provides time zone selection functions. Use them to build the time zone selection logic that makes sense for you.

You can try setting timezone cookie via javascript by utilizing getTimezoneOffset function or try to do some geoip magic and figure timezone by location. Probably the most reliable way would be to ask the user directly and save this information in user profile/session.

Solution 2

I've simplified it even further, and you can plug in in here: https://github.com/Miserlou/django-easy-timezones or http://gun.io/blog/django-easy-timezones/

Solution 3

I was hunting around for the sam thing yesterday. In the end I ended up putting together a Django app to what BluesRockAddict suggests above (i.e. use getTimezoneOffset):

https://github.com/adamcharnock/django-tz-detect

I hope someone finds that useful.

Solution 4

There is a nice APP for django to activate timezone https://pypi.python.org/pypi/django-visitor-information-middleware/0.1.0. Which having two middleware

TimezoneMiddleware

The middleware activates a timezone for an authenticated user.

VisitorInformationMiddleware

This middleware adds the following keys to the request.visitor dictionary:

country - country the visitor is based in.

city - city the visitor is based in

location.timezone - timezone used in the location visitor is based in

location.unit_system - unit system used in the location visitor is based in

user.timezone - timezone of the currently authenticated user

user.unit_system - unit system of the currently authenticated user.

cookie_notice - True if a cookie consent notice should be displayed for the current visitor.

Note: Location of the user is determined based on the user's IP address.

Solution 5

I currently created a middleware class (following Django's documentation) in which I rely on MaxMind geoip database (http://dev.maxmind.com/geoip/legacy/geolite) and GeoDjango (https://docs.djangoproject.com/en/1.5/ref/contrib/gis/) to retrive user's country code and then set the timezone dynamically using pytz:

class TimezoneMiddleware(object):


    def __getUserTimeZone(self, request):
        info = IPResolver(request).getGeoInfo()
        return pytz.country_timezones[info['country_code']][0]


    def process_request(self, request):
        try:
            tz = self.__getUserTimeZone(request)
            timezone.activate(tz)
            logger.debug('Time zone "%s" activated' % str(tz))
        except Exception as e:
            logger.error('Unable to set timezone: %s' % str(e))

pytz.country_timezones returns a collection of time zones available for the given country, so I basically choose the first one returned.

IPResolver is a personal utility class I wrote on top of django.contrib.gis.utils.GeoIP

Share:
23,833
xpanta
Author by

xpanta

Programming in Python, Java, Delphi.

Updated on April 09, 2020

Comments

  • xpanta
    xpanta about 4 years

    I would like to know if there is a way to automatically retrieve user's timezone from client. Especially during login.

    I tried to add this in the login page (using auth.login):

    {% get_current_timezone as TIME_ZONE %}
    

    and then add this in the login form

    <input type="hidden" name="next" value="/redirect/?tz={{ TIME_ZONE }}">
    

    but tz is always the timezone of the server.

    • dgel
      dgel about 12 years
      This was discussed (and argued about) at length in another SO question..
  • sage
    sage almost 9 years
    It's worth noting that this is available by pip and that there are step-by-step instructions. I have it working after only a few minutes. Thanks!
  • sage
    sage almost 9 years
    Before you try to do 'geoip magic', take a look at @Rich's answer - it only took me a few minutes to pip install and configure his plugin.
  • Igor Yalovoy
    Igor Yalovoy about 7 years
    Any idea about performance impact? Especially in terms of response time.
  • Igor Yalovoy
    Igor Yalovoy about 7 years
    Any idea about performance impact? Especially in terms of response time.
  • iri
    iri over 3 years
    django-easy-timezones uses an out of date database that is no longer available for download. Use django-easy-timelines-redux instead.
  • Thismatters
    Thismatters about 2 years
    It is also worth noting that this package uses the client's IP address to look up the timezone, it isn't referencing the timezone setting of the client.