Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django DateTimeField auto_now_add not working

In one of the model i have set one timestamp field as follows:

created_datetime = models.DateTimeField(auto_now_add = True)

While in shell i am able to create a obj and save it, however in my application it is raising a exception that created_datetime field cannot be null.

Confused where things went wrong!! How to reslove it.

like image 774
Arun Avatar asked May 05 '11 14:05

Arun


People also ask

What is Auto_now_add in Django?

auto_now_add. Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it's not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored.

What is difference between Auto_now and Auto_now_add?

auto_now - updates the value of field to current time and date every time the Model. save() is called. auto_now_add - updates the value with the time and date of creation of record.


1 Answers

As far as I know, best practice for default datetimes is to use the following:

created_datetime = models.DateTimeField(default=datetime.datetime.now)

Don't forget to import datetime

like image 174
Alex Jillard Avatar answered Sep 16 '22 12:09

Alex Jillard