简体   繁体   中英

How to set the current proper date and time to "DateField()" and "TimeField()" respectively as a default value by "TIME_ZONE" in Django Models?

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.

The problem is that you set USE_TZ as True .

If USE_TZ is set as True , regardless of what your TIME_ZONE variable is set to, Django will only use the UTC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM