Created
March 23, 2021 15:52
-
-
Save pirate/306b36d02e5a661f5fc4ba2b265c647c to your computer and use it in GitHub Desktop.
Automatic timezone detection based on the user's browser for Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Inspiration from here: https://tutti.me/post/5453/ | |
# Or you can use a library like: | |
# - https://github.com/adamcharnock/django-tz-detect (last updated 2019) | |
# - https://github.com/Miserlou/django-easy-timezones (last updated 2016) | |
# - https://github.com/jamesmfriedman/django-easytz (last updated 2015) | |
# Or guess TZ using visitors IP GEOIP: https://codereview.stackexchange.com/questions/161261/set-time-zone-from-cookie | |
# settings.py | |
TEMPLATES = [{ | |
... | |
'OPTIONS': { | |
'context_processors': [ | |
... | |
'myapp.context_processors.timezone_processor', | |
], | |
}, | |
}] | |
from django.utils import timezone | |
def timezone_processor(request): | |
# look for a cookie that we expect to have the timezone | |
tz = request.COOKIES.get('local_timezone', None) | |
if tz: | |
tz_int = int(tz) # cast to int | |
# here we decide what will prefix timezone number | |
# the output of tz_str will be something like: | |
# Etc/GMT+1, GMT+0, Etc/GMT-2 | |
if tz_int >= 0: | |
tz_str = 'Etc/GMT+'+tz | |
else: | |
tz_str = 'Etc/GMT'+tz | |
# this forces timezone | |
timezone.activate(tz_str) | |
# Now we tell the template that we have a timezone | |
return {'local_timezone': tz} | |
# templates/base.html | |
... | |
{% if not local_timezone %} | |
<script> | |
document.cookie = 'local_timezone=" + (new Date().getTimezoneOffset() / 60); | |
</script> | |
{% endif %} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment