Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Django user timezones
from django.conf import settings
from django.utils import timezone
import pygeoip
import pytz
db_loaded = False
db = None
def load_db():
global db, db_loaded
db = pygeoip.GeoIP(settings.GEOIP_DATABASE, pygeoip.MEMORY_CACHE)
db_loaded = True
def get_client_ip(request):
return request.META.get('REMOTE_ADDR')
class TimezoneMiddleware(object):
def process_request(self, request):
if request.user and request.user.is_authenticated() and \
request.user.timezone in pytz.all_timezones:
tzname = request.user.timezone
else:
if not db_loaded:
load_db()
tzname = db.time_zone_by_addr(get_client_ip(request))
if not tzname in pytz.all_timezones:
tzname = timezone.get_default_timezone()
timezone.activate(tzname)
request.timezone = tzname
def process_response(self, request, response):
timezone.deactivate()
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment