Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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

like image 529
Shamanu4 Avatar asked May 05 '10 08:05

Shamanu4


People also ask

What is Django default datetime format?

django default date to be in format %d-%m-%Y.

How do I use datetime in Django?

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.

What is Auto_now_add in Django?

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.


2 Answers

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

like image 186
Carson Myers Avatar answered Sep 30 '22 15:09

Carson Myers


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

Reference:

  • Documentation for django.utils.timezone.now

so go for something like this:

from django.utils.timezone import now   created_date = models.DateTimeField(default=now, editable=False) 
like image 27
andilabs Avatar answered Sep 30 '22 16:09

andilabs