Search code examples
djangodatabase-migrationdjango-1.8

datetime fields not migrating with django 1.8


Since upgrading to django 1.8 I've been having some issues with datetime fields in my models not migrating correctly.

I was seeing this message repeatedly:

Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

I run makemigrations and I get this:

operations = [
    migrations.AlterField(
        model_name='profile',
        name='date_of_hire',
        field=models.DateField(default=datetime.date(2016, 6, 5)),
    ),
]

So I run manage.py migrate and then i get:

Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

So I run make migrations again and I get an new migration identical to the one above.

here's my problem field:

date_of_hire = models.DateField(default=datetime.date.today())

Looking at the migration I can see that the date is getting explicitly set to a fixed date. So now if I change my field to this:

date_of_hire = models.DateField(auto_now_add=True)

or this:

date_of_hire = models.DateTimeField(auto_now_add=True)

I get the error below when trying to run makemigrations or start my server:

File "/urls.py", line 13, in <module>
import profiles.views as profile_views
File "/profiles/views.py", line 9, in <module>
from profiles.forms import CompanyProfileForm
File "/profiles/forms.py", line 19, in <module>
class ProfileForm(ModelForm):
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 295, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (date_of_hire) specified for Profile

If I comment out that field in the forms.py fields list everything except the for the form works. I can make migrations and apply them, run the server, etcetera, but as soon as I uncomment that field the app take a crap. So I am at a loss...


Solution

  • In your default, you should pass the callable datetime.date.today, instead of calling it:

    date_of_hire = models.DateField(default=datetime.date.today)
    

    When you use default=datetime.date.today(), Django calls today() every time you load your models.py. This changes the default, so Django thinks a new migration is required.

    You'll have to create one more migration to change the default to datetime.date.today (or edit the existing migrations but that will be trickier).