0

I'm new to django and is working on an application that can store user notes and reminder time. I have followed the Django document(https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/) and added TimezoneMiddleware to middleware, set_timezone method, and timezone template. But still not able to get the correct user timezone, it always shows as UTC.

I'm not sure if there anything need to be add in frontend part? because as in code:

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

def __call__(self, request):
    tzname = request.session.get('django_timezone')
    if tzname:
        timezone.activate(pytz.timezone(tzname))
    else:
        timezone.deactivate()
    return self.get_response(request)

it seems should get timezone information from session data, but I have checked and there no timezone information there.

Would anyone suggest what I might missed? Thank you.

Lodye
  • 11
  • 1
  • 3

1 Answers1

0

Create a middleware:

class TimezoneMiddleware(object):

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

    def __call__(self, request):
        if request.user.is_authenticated:
            tz_str = request.user.country.code
            if tz_str:
                time_zone_countries = pytz.country_timezones(tz_str)
                for time_zone_l in time_zone_countries:
                    timezone.activate(pytz.timezone(time_zone_l))
            else:
                timezone.deactivate()
        else:
            timezone.deactivate()

        response = self.get_response(request)
        return response

Requirements:

  • Thank you! Just wondering is it possible to get timezone based on user current timezone, which no need to save timezone information into table? – Lodye Nov 25 '21 at 00:12
  • Check this: https://stackoverflow.com/a/65180937/16350436 –  Nov 25 '21 at 01:55
  • yeah i have added all of those. but still not able to get timezone except UTC. But thank you. – Lodye Nov 25 '21 at 04:03