Django datetime issues (default=datetime.now()) Django datetime issues (default=datetime.now()) python python

Django datetime issues (default=datetime.now())


it looks like datetime.now() is being evaluated when the model is defined, and not each time you add a record.

Django has a feature to accomplish what you are trying to do already:

date = models.DateTimeField(auto_now_add=True, blank=True)

or

date = models.DateTimeField(default=datetime.now, blank=True)

The difference between the second example and what you currently have is the lack of parentheses. By passing datetime.now without the parentheses, you are passing the actual function, which will be called each time a record is added. If you pass it datetime.now(), then you are just evaluating the function and passing it the return value.

More information is available at Django's model field reference


Instead of using datetime.now you should be really using from django.utils.timezone import now

Reference:

so go for something like this:

from django.utils.timezone import nowcreated_date = models.DateTimeField(default=now, editable=False)


From the documentation on the django model default field:

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

Therefore following should work:

date = models.DateTimeField(default=datetime.now,blank=True)


matomo