Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change time zone depending on the user in django project

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()
like image 487
Alejandroid Avatar asked Apr 19 '18 06:04

Alejandroid


People also ask

How do I change the timezone in Django project?

Time zone support is disabled by default. To enable it, set USE_TZ = True in your settings file. In Django 5.0, time zone support will be enabled by default. Time zone support uses zoneinfo , which is part of the Python standard library from Python 3.9.

How does Python handle different time zones?

The parameter pytz. timezone allows us to specify the timezone information as a string. We can pass in any available timezone and will get the current date time of that timezone, and it will also print the offset with respect to the UTC. i.e., the difference between UTC timezone(+00:00) and the specified time zone.


1 Answers

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

like image 173
Sir Skizo Avatar answered Oct 05 '22 23:10

Sir Skizo