Change time zone depending on the user in django project
Asked Answered
F

1

8

I am trying to change the time zone in my project, depending on what the user has selected.

To do that I have a field in my database, where I keep all possible locations:

timezone = models.CharField(max_length=40, null=True, blank=True, choices=[(n,n) for n in pytz.all_timezones])

but the problem is that when I try to change the time zone it does not work.

---- setting.py ----

USE_TZ = True
TIME_ZONE = 'Europe/Madrid'

---- Dashboard (view.py) ----> output

@login_required
def dashboard(request):
    from datetime import datetime, timedelta    
    import pytz

    print "Normal:" + str(datetime.now()) # Normal:2018-04-19 08:39:51.484283
    print "TimeZone:" + str(timezone.now()) # TimeZone:2018-04-19 06:39:51.484458+00:00

    u = User.objects.get(user=request.user) # u: Alejandroid
    timezone_selected = u.timezone # timezone_selected: u'Canada/Saskatchewan'
    timezone.activate(pytz.timezone(timezone_selected))

    print "Normal:" + str(datetime.now()) # Normal:2018-04-19 08:40:02.829441
    print "TimeZone:" + str(timezone.now()) # TimeZone:2018-04-19 06:40:04.329379+00:00

As you can see, it only returns me the local time defined in TIME_ZONE and in UTC time.

I'm working with Django 1.8

How do I make it work?

Thank you very much.



My solution

You need to create a middleware.

class TimezoneMiddleware(object):

    def process_request(self, request):
        from django.utils import timezone
        import pytz
        from settings import TIME_ZONE
            if request.user.is_authenticated():
                timezone_selected = request.user.timezone
                if not timezone_selected:
                    timezone_selected = TIME_ZONE
                timezone.activate(pytz.timezone(timezone_selected))
            else:
                timezone.deactivate()
Finn answered 19/4, 2018 at 6:47 Comment(1)
From where are you selecting the timezone, is this like a type of user profile field or is the .timezone an attribute inside the request object?Optic
Z
0

The Django settings assume that you are going to work with datatime:

from datetime import datetime

datetime.now()

or

datetime.now().strftime("%Y/%m/%d %H:%M")

Just use these functions instead timezone.now()

and in settings.py add:

USE_TZ = True TIME_ZONE = 'UTC' # UTC == madrid/europe

Zaid answered 22/11, 2020 at 16:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.