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()
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With