Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which timezone does Django use in DateField's auto_now_add?

How does Django write the date field when the field is marked with auto_now_add attribute?

Is it like datetime.now().date() or timezone.now().date()?

In other words, which timezone does it use to get the current date?

like image 930
NeoWang Avatar asked Oct 03 '14 15:10

NeoWang


1 Answers

Looks like it uses datetime.date.today(), which would be the local date of the system:

db/models/fields/__init__.py:

class DateField(Field):
    ...
    def pre_save(self, model_instance, add):
        if self.auto_now or (self.auto_now_add and add):
            value = datetime.date.today()
            setattr(model_instance, self.attname, value)
            return value

If you wanted a different behavior you could remove auto_now_add=True then connect the model's pre_save signal to a receiver that would set your field to the date of your choice.

Alternatively, you could override the model's save method and set the field there.

like image 130
dgel Avatar answered Sep 30 '22 09:09

dgel