I needed something similar today at work. Default value to be timezone.now()
, but editable both in admin and class views inheriting from FormMixin
, so for created in my models.py
the following code fulfilled those requirements:
from __future__ import unicode_literals
import datetime
from django.db import models
from django.utils.functional import lazy
from django.utils.timezone import localtime, now
def get_timezone_aware_now_date():
return localtime(now()).date()
class TestDate(models.Model):
created = models.DateField(default=lazy(
get_timezone_aware_now_date, datetime.date)()
)
For DateTimeField
, I guess remove the .date()
from the function and change datetime.date
to datetime.datetime
or better timezone.datetime
. I haven't tried it with DateTime
, only with Date
.