This app will auto-detect a user's timezone using JavaScript, then configure Django's timezone localization system accordingly. As a result, dates shown to users will be in their local timezones.
Authored by Adam Charnock, and some great contributors.
On the first page view you should find that tz_detect
places a
piece of asynchronous JavaScript code into your page using the
template tag you inserted. The script will obtain the user's GMT
offset using getTimezoneOffset
, and post it back to Django. The
offset is stored in the user's session and Django's timezone awareness
is configured in the middleware.
The JavaScript will not be displayed in future requests.
Either checkout
tz_detect
from GitHub, or install using pip:pip install django-tz-detect
Add
tz_detect
to yourINSTALLED_APPS
:INSTALLED_APPS += ( 'tz_detect', )
Be sure you have the
django.template.context_processors.request
processorTEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.request', ], }, }, ]
Update your
urls.py
file:urlpatterns += [ path('tz_detect/', include('tz_detect.urls')), ]
Add the detection template tag to your site, ideally in your base layout just before the
</body>
tag:{% load tz_detect %} {% tz_detect %}
Add
TimezoneMiddleware
toMIDDLEWARE
:import django MIDDLEWARE += ( 'tz_detect.middleware.TimezoneMiddleware', ) if django.VERSION < (1, 10): MIDDLEWARE_CLASSES += ( 'tz_detect.middleware.TimezoneMiddleware', )
(Optional) Configure optional settings
Set the countries in which your app will be most commonly used:
# These countries will be prioritized in the search # for a matching timezone. Consider putting your # app's most popular countries first. # Defaults to the top Internet using countries. TZ_DETECT_COUNTRIES = ('CN', 'US', 'IN', 'JP', 'BR', 'RU', 'DE', 'FR', 'GB')
Set the session key that will be used to store the detected timezone
# Session key to use, defaults to "detected_tz" TZ_SESSION_KEY = "my-session-key"
Please see example
application. This application is used to manually
test the functionalities of this package. This also serves as a good
example.
You need only Django 1.8 or above to run that. It might run on older versions but that is not tested.
- Django's timezone awareness will not be available on the first page view
- This method requires JavaScript
- Timezone detection is done entirely from the user's GMT offset, not from their location
- A hook to allow the timezone to be stored against a user
- Allow timezones to be manually specified
- Improve timezone detection
- Optionally using HTML5's location API for better timezone determination