15

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.

Arun
  • 836
  • 1
  • 12
  • 19
  • Better use a custom `save()` rather than using `auto_now_add`. [Read this.](http://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add) – Konstant May 05 '11 at 15:07

5 Answers5

15

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

Alex Jillard
  • 2,792
  • 2
  • 19
  • 20
4

I had this and it really confused me for ages.

Turned out that my model had a custom primary key, and it was due to a bug not setting it when constructing some test objects.

The first time this worked fine as auto_now_add set created_at. The second time it didn't as the object with a null primary key already existed, so it was doing an update. And it tried to set that to created_at null, which wasn't allowed in my model.

So worth checking if you end up on this question with the error "in my application it is raising a exception that created_datetime field cannot be null", that that could be caused by not setting a primary key correctly.

The solution was for me to correctly set a primary key.

frabcus
  • 919
  • 1
  • 7
  • 18
  • 1
    Thanks so much for this comment, it helped me out. My case was that I was reusing a primary key to make a new record, and django/sqlite for some reason didn't say "you cannot reuse that key", instead it complained about the created_at field. Your hint here really saved me a lot of time. – rossdavidh Apr 08 '20 at 17:29
3

You can do something like this

created_datetime = models.DateTimeField(auto_now_add=True, auto_now=False)
Ashish
  • 96
  • 3
0
data_obj = Organization.objects.get(id=id)
.....
created_at = data_obj.created_at

It means call your old saved created_at data from database and re-save again during Updation created_at fields not working so save it statically, no need to do dynamically. My model is created_at = models.DateTimeField(auto_now_add=True)

Ronny Dsouza
  • 358
  • 2
  • 12
-2

The following way is in the "part1" of django documentation

from django.utils import timezone
p = Poll(question="What's new?", pub_date=timezone.now())