I try to prepopulate a TimeField in django_admin with the following code :
from django.utils import timezone
time_start = models.TimeField('Heure de debut',max_length=20, default=timezone.now)
I've installed pytz and also correctly set
TIME_ZONE = 'Europe/Brussels'
USE_TZ = True
and the "now" button in admin correctly sets the time if I click on it. However, it initialy shows the time in UTC (two hours before the actual time in my case)
Am I missing something and is there a way to solve this ? I don't want to use auto_now_add=False because I want to be able to change this time later...
The solution to this problem is to use UTC in the code and use local time only when interacting with end users. 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.
utils. tzinfo , is a support system within Django that stores data and time information in UTC in the database. It uses the time-zone-aware- datetime objects internally and translates them to the user's time zone in templates.
When USE_TZ is False, this is the time zone in which Django will store all datetimes. When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms. ... When django rest framework takes the naive datetime data from request.
To get Time in local timezone as set in settings.py use:
from django.utils import timezone
timezone.localtime(timezone.now())
As for use in django models see this answer here https://stackoverflow.com/a/12654998/1340421
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