[Django]-Django-tz-detect automatically save timezone to user model

2👍

This can be accomplished with simple custom middleware.

Make sure you’re using django-tz-detect.

INSTALLED_APPS = [
    # ...
    'tz_detect',
    'myapp.apps.MyappConfig',
]

Add your own middleware to the stack, after django-tz-detect.

MIDDLEWARE = [
    # ...
    'tz_detect.middleware.TimezoneMiddleware',
    'myapp.middleware.UserTimezoneMiddleware',
]

myapp/middleware.py

from django.utils import timezone

class UserTimezoneMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        if request.user.is_authenticated:
            if request.session.get('detected_tz'): # (set by django-tz-detect)
                tz = timezone.get_current_timezone()
                if tz:
                    tz = str(tz)
                    # (this assumes your user model has a char field called "timezone")
                    if tz != request.user.timezone:
                        request.user.timezone = tz
                        request.user.save()

        return response

Timezone strings (e.g. "America/Chicago") are now automatically saved to the user model, and updated if the user logs in from a different tz.

Leave a comment