Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, DateTimeField(auto_now_add=True) not working

Tags:

django

I am a newbie of Django. This is the problem I have encountered.

models.py: created_time = models.DateTimeField('Created Time', auto_now_add=True) When I migrations: migrations error

Then, I add the default to it: created_time = models.DateTimeField('Created Time', auto_now_add=True, default=timezone.now) I migrations it again: migrations error2

So, can somebody tell me how to use DateTimeField with auto_now_add=True?

like image 382
lizs Avatar asked Oct 15 '25 19:10

lizs


1 Answers

As the error says, you can't set auto_now_add=True and specify a default at the same time.

The problem is that Django needs to know what value to use for your existing entries in the database.

You can either set null=True, then the value will be left as None.

created_time = models.DateTimeField('Created Time', auto_now_add=True, null=True)

Or, simply remove the default, and run makemigrations again.

created_time = models.DateTimeField('Created Time', auto_now_add=True)

When Django prompts you, select Option 1), and specify a default (e.g. timezone.now).

like image 84
Alasdair Avatar answered Oct 18 '25 16:10

Alasdair