from __future__ import annotations from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from django.utils import timezone class UserTimezoneMiddleware: """Activate the visitor's selected timezone (defaults to UTC). Everything is stored in UTC; this is the only place display time is chosen, so a page that renders a naive local time is a bug in the template, not here. """ SESSION_KEY = "user_timezone" DEFAULT_TIMEZONE = "UTC" def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tz_name = request.session.get(self.SESSION_KEY, self.DEFAULT_TIMEZONE) try: timezone.activate(ZoneInfo(tz_name)) request.current_timezone_name = tz_name except (ZoneInfoNotFoundError, ValueError): timezone.activate(ZoneInfo(self.DEFAULT_TIMEZONE)) request.current_timezone_name = self.DEFAULT_TIMEZONE response = self.get_response(request) timezone.deactivate() return response