Alexander
Alexander

Reputation: 727

Updating django models

I added a new field to an existing model. When I use the command "manage.py makemigrations myapp" I get the following error:

You are trying to add a non-nullable field 'slug' to post without a default. we can not do that < the database needs something to populate existing rows>. 

What should be the default value for the new field slug? Here is my model:

class Post(models.Model):
    title = models.CharField(max_length = 100, null = False, blank = False)
    body = models.TextField()
    dateCreated = models.DateTimeField(default=datetime.now, blank=True)
    slug = models.SlugField(unique = True)

    def __str__(self):
        return self.title

Upvotes: 0

Views: 353

Answers (2)

Selcuk
Selcuk

Reputation: 59445

You cannot add a not-null field to an existing model without a default value. If you must make it not-null, you should:

  1. Add the field using null=True
  2. Migrate your database
  3. Populate existing rows
  4. Remove null=True
  5. Migrate again

Upvotes: 1

argaen
argaen

Reputation: 4255

This is because you are trying to create a migration with a non nullable field, that's why it is asking to provide a default value. Since it is a slug field, I would set it to null=True and blank=False and try again.

Also, you may want to set prepopulated_fields in your Django admin.py file.

PS: You don't have to specify null = False and blank = False since those values are the default ones.

Upvotes: 2

Related Questions