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()