The doc says below in DateField.auto_now_add. *I use Django 4.2.1:
Automatically set the field to now when the object is first created. ... If you want to be able to modify this field, set the following instead of
auto_now_add=True
:
- For
DateField
:default=date.today
-from datetime.date.today()
- For
DateTimeField
:default=timezone.now
-from django.utils.timezone.now()
So, I set timezone.now and date.today to datetime
's DateTimeField() and date1
's DateField() respectively and I also set current_date
which returns timezone.now().date()
and current_time
which returns timezone.now().time()
to date2
's DateField()
and time
's TimeField() respectively as shown below:
# "models.py"
from django.db import models
from datetime import date
from django.utils import timezone
def current_date():
return timezone.now().date()
def current_time():
return timezone.now().time()
class MyModel(models.Model):
datetime = models.DateTimeField(default=timezone.now) # Here
date1 = models.DateField(default=date.today) # Here
date2 = models.DateField(default=current_date) # Here
time = models.TimeField(default=current_time) # Here
Then, I set 'America/New_York'
to TIME_ZONE in settings.py
as shown below:
# "settings.py"
LANGUAGE_CODE = "en-us"
TIME_ZONE = 'America/New_York' # Here
USE_I18N = True
USE_L10N = True
USE_TZ = True
But, date1
's DateField()
and time
's TimeField()
show UTC(+0 hours)'s date and time respectively on Django Admin as shown below:
Next, I set 'Asia/Tokyo'
to TIME_ZONE
in settings.py
as shown below:
# "settings.py"
LANGUAGE_CODE = "en-us"
TIME_ZONE = 'Asia/Tokyo' # Here
USE_I18N = True
USE_L10N = True
USE_TZ = True
But, date2
's DateField()
and time
's TimeField()
show UTC(+0 hours)'s date and time on Django Admin as shown below:
So, how can I set the current proper date and time to DateField()
and TimeField()
respectively as a default value by TIME_ZONE
in Django Models?
In addition, DateField()
and TimeField()
with auto_now or auto_now_add cannot save UTC(+0 hours)'s date and time respectively with any TIME_ZONE
settings.