Search code examples
pythondjangotimezonepytzdjango-timezone

Django Time Zone issue


I'm having lot's of troubles with TimeZones in my Django application.

For explanation purposes I'll jump right to the example :

I have an object which has a TimeField(null=True, blank=True), and I basically want to show this time depending on the users timezone.

I have a Middleware class which activates the timezone to the authenticated user :

#'middleware.py'


import pytz

from django.utils import timezone


class TimezoneMiddleware(object):
    """
    Middleware to properly handle the users timezone
    """

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

    def __call__(self, request):
        if request.user.is_authenticated:
            timezone.activate(pytz.timezone(request.user.timezone))
        else:
            timezone.deactivate()

        response = self.get_response(request)
        return response

Next to this, I'm pulling timezones from User model field timezone = models.CharField(max_length=128, choices=[(tz, tz) for tz in ['UTC'] + pytz.country_timezones('US')], default="UTC") which basically tells me the timezone user selected.

And that's all good until I need to render the time adopted to the users timezone.

So In my case user has the 'Pacific/Honolulu' timezone. Object time field was saved to 'American/New_York' timezone, and I'm still getting the same time no matter which timezone I select.

What am I doing wrong?

(I was fallowing the official docs for this)

This is my template :

{% load tz %}
{% get_current_timezone as TIME_ZONE %}

{% for object in objects %}
    {% localtime on %}
        {{ object.min_reservation_time }}
    {% endlocaltime %}
{% endear %}

Also - when I try to render {{TIME_ZONE}} in this exact template - I get nothing.

This is my settings.py :

TIME_ZONE = 'UTC' # Default timezone if custom timezone is not activated by middleware

USE_I18N = True

USE_L10N = True

USE_TZ = True

So one more time, users selects the timezone, middleware process it if the user is logged in, and ...nothing changes for some reason.


Solution

  • You'd be doing the right things—if you had a DateTimeField. But, as the documentation says:

    Django only supports naive time objects and will raise an exception if you attempt to save an aware time object, as a timezone for a time with no associated date does not make sense.

    So none of Django's time zone support applies to a TimeField. If you really do want to use a TimeField, and adjust the values depending on the user's timezone, you'll have to do so manually.