You are trying to add a non-nullable field 'new_field' to userprofile without a default

I know that from Django 1.7 I don't need to use South or any other migration system, so I am just using simple command python manage.py makemigrations

However, all I get is this error:

You are trying to add a non-nullable field 'new_field' to userprofile without a default;
we can't do that (the database needs something to populate existing rows).

Here is models.py:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField(blank=True)
    new_field = models.CharField(max_length=140)

What are options?


Solution 1:

You need to provide a default value:

new_field = models.CharField(max_length=140, default='SOME STRING')

Solution 2:

If you are in early development cycle and don't care about your current database data you can just remove it and then migrate. But first you need to clean migrations dir and remove its rows from table (django_migrations)

rm  your_app/migrations/* 

Note: Don't delete _ _ init _ _ .py in the migrations folder.

rm db.sqlite3
python manage.py makemigrations
python manage.py migrate

If you previously created a superuser for Django's Admin web app then you might need to create the user again.

Solution 3:

One option is to declare a default value for 'new_field':

new_field = models.CharField(max_length=140, default='DEFAULT VALUE')

another option is to declare 'new_field' as a nullable field:

new_field = models.CharField(max_length=140, null=True)

If you decide to accept 'new_field' as a nullable field you may want to accept 'no input' as valid input for 'new_field'. Then you have to add the blank=True statement as well:

new_field = models.CharField(max_length=140, blank=True, null=True)

Even with null=True and/or blank=True you can add a default value if necessary:

new_field = models.CharField(max_length=140, default='DEFAULT VALUE', blank=True, null=True)

Solution 4:

In case anyone is setting a ForeignKey, you can just allow nullable fields without setting a default:

new_field = models.ForeignKey(model, null=True)

If you already have data stored within the database, you can also set a default value:

new_field = models.ForeignKey(model, default=<existing model id here>)