So I just deployed a django
web app but to my surprise, it records all time objects with UTC +0
. ALL OF THEM! no matter the user's timezone
.
I have USE_TZ = True
in settings. Here are the places I'm inserting time.
Model.py
class Timesheet(models.Model):
....
start_date = models.DateTimeField(default=timezone.now)
....
def save(self, *args, **kwargs):
entry = Timesheet.objects.filter(id=self.request.user)
if entry.exists():
Timesheet.objects.filter(id=self.request.user).update(end_date=timezone.now())
...
super().save(*args, **kwargs)
How do I make it use the timezone of the user all across U.S.?
I don't partially understand what you want to do in Model.py but when you have USE_TZ=True
in your settings, Django will automatically convert all datetime objects to UTC when they're saved to the database and convert them back to the user's timezone when they're displayed.
On the other hand, keep in mind that the United States has different time zones, if you are interested in displaying data in your user's time zone you can use a helper like the following:
# Django
from django.utils import timezone
def get_user_timezone_now():
user_timezone = timezone.get_current_timezone()
return timezone.now().astimezone(user_timezone)
This is as long as you have a middleware by which you can get the timezone of your user as the official documentation says.
import zoneinfo
from django.utils import timezone
class TimezoneMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
tzname = request.session.get('django_timezone')
if tzname:
timezone.activate(zoneinfo.ZoneInfo(tzname))
else:
timezone.deactivate()
return self.get_response(request)