I have the below db model:
from datetime import datetime class TermPayment(models.Model): # I have excluded fields that are irrelevant to the question date = models.DateTimeField(default=datetime.now(), blank=True)
I add a new instance by using the below:
tp = TermPayment.objects.create(**kwargs)
My issue: all records in database have the same value in date field, which is the date of the first payment. After the server restarts, one record has the new date and the other records have the same as the first. It looks as if some data is cached, but I can't find where.
database: mysql 5.1.25
django v1.1.1
django default date to be in format %d-%m-%Y.
First, open the views.py file of your Django application and import the datetime module. Next, use the datetime. now() method to get the current date and time value. Now, we can either assign this method to a variable or we can directly use this method wherever we required the datetime value.
The auto_now_add will set the timezone. now() only when the instance is created, and auto_now will update the field everytime the save method is called. It is important to note that both arguments will trigger the field update event with timezone.
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
django.utils.timezone.now
so go for something like this:
from django.utils.timezone import now created_date = models.DateTimeField(default=now, editable=False)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With