1

The doc says below in DateField.auto_now_add:

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 to DateField() and DateTimeField(), I can set the current date and time respectively as a default value as shown below:

from datetime import date
from django.utils import timezone

class MyModel(models.Model):
    date = models.DateField(default=date.today) # Here
    datetime = models.DateTimeField(default=timezone.now) # Here

Now, how can I set the current time to TimeField() as a default value as shown below?

class MyModel(models.Model):       # ?
    time = models.TimeField(default=...)
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129

2 Answers2

1

You can use a callable:

from django.utils import timezone


def current_time():
    return timezone.now().time()


class MyModel(models.Model):
    time = models.TimeField(default=current_time)

each time you define a new MyModel and the time is not passed, it will call the current_time method and thus return the time component of the current (timezoned time).

It is important not to use parenthesis, so default=current_time, not default=current_time().

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

You can set current_time without () which returns timezone.now().time() to TimeField() as a default value as shown below. *Don't set current_time() with () because the default time becomes when the Django server starts (Unchanged):

from django.utils import timezone

def current_time(): # Here
    return timezone.now().time()

class MyModel(models.Model): # Don't set "current_time()"
    time = models.TimeField(default=current_time)

Be careful, don't set timezone.now().time() with () to TimeField() as a default value as shown below because the default time becomes when the Django server starts (Unchanged):

from django.utils import timezone

class MyModel(models.Model): # Don't set "timezone.now().time()"
    time = models.TimeField(default=timezone.now().time())

And, don't set timezone.now().time without () to TimeField() as a default value as shown below because there is an error when running python manage.py makemigrations:

from django.utils import timezone

class MyModel(models.Model): # Don't set "timezone.now().time"
    time = models.TimeField(default=timezone.now().time)

In addition, I don't recommend to use DateField() and TimeField() because they don't work with TIME_ZONE in settings.py as I asked the question while DateTimeField() does.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129