# Imports
from django.conf import settings
from django.utils import timezone
import pytz
# Exports
__all__ = (
"TimeZoneMiddleware",
)
# Constants
TIMEZONE_KEY = getattr(settings, "SUPERDJANGO_TIMEZONE_KEY", "django_timezone")
"""The session key used to identify the user's timezone."""
# Classes
[docs]class TimeZoneMiddleware:
"""Set the current time zone; either that of the user or the system default.
This is pretty much straight from the example found in Django documentation, but with new-style middleware.
See: https://docs.djangoproject.com/en/stable/topics/i18n/timezones/#selecting-the-current-time-zone
"""
[docs] def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
timezone_name = request.session.get(TIMEZONE_KEY)
if timezone_name:
timezone.activate(pytz.timezone(timezone_name))
elif hasattr(settings, "TIME_ZONE") and settings.USE_TZ:
timezone.activate(pytz.timezone(settings.TIME_ZONE))
else:
timezone.deactivate()
return self.get_response(request)