I am trying to work with the Django Timezone Middleware which I took from the offical documentation, but it doesn't seem to work.
I have a middleware.py file like this:
import pytz
from django.utils import timezone
class TimezoneMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
tzname = request.session.get('django_timezone')
print('DJANGO TIMEZONE', tzname)
if tzname:
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
return self.get_response(request)
Where I output the "tzname" to the console, it is set to None which must be the problem, but why isn't it set?
My settings file has the following:
USE_TZ = True
TIME_ZONE = "UTC"
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'myproject.middleware.TimezoneMiddleware',
]
My template looks like this:
{% load tz %}
{% get_current_timezone as TIME_ZONE %}
{{ TIME_ZONE }}
{% localtime on %}
<p>{{ room.open_date }}</p>
{% endlocaltime %}
The result is that {{ room.open_date }} will show in UTC. {{ TIME_ZONE }} displays 'UTC'. I have tried without the TIME_ZONE setting in settings. I believe I have implemented it according to the documentation, but am obviously missing something. My Django version is Django version 3.2.5.
Please can someone help. My goal is to display the dates in the timezone that the browser has.