You are trying to add a non-nullable field 'id' to contact_info without a defaultt

Viewed 33

I am using the command python manage.py makemigrations

However, I get this error:

You are trying to add a non-nullable field 'id' to contact_info without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py

Here is models.py:

class Posts(models.Model):
    id = models.AutoField(primary_key=True)
    post_uesr = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,related_name='create_user')
    post_title = models.CharField(max_length=200)
    post_description = models.TextField(max_length=800, null=True, blank=True)
    post_likes = models.IntegerField(default=0)
    post_date = models.DateTimeField(default=datetime.now)

    def __str__(self):
        return f'{self.post_uesr}'
2 Answers

It's not a bug, it's documented and logical. You add a new field, which is (by best practice, as you noticed) not NULLable so django has to put something into it for the existing records .

You can press 1 so this option applies

 1) Provide a one-off default now (will be set on all existing rows)

so just press 1, if thats your case as value. else if you want to abort this task and provide manually press 2 and this option applies.

 2) Quit, and let me add a default in models.py

BUT here in your case id is a default field already included in every table you create and that will be default to primary key.

And if you are looking to add another AutoField probably this will help

order = models.AutoField(primary_key=False)

And if you are trying to make primary key as uuid4 format

import uuid
id = models.AutoField(default=uuid.uuid4, primary_key=True)

it's telling you should specified a default value for your id field.

ask you for adding manually a default value to this field or make a field without any default value in database.

for example for using UUID as your post id you should do like this:

import uuid

from django.db import models

class Posts(models.Model):
    id = models.AutoField(default=uuid.uuid4, primary_key=True)
    # other lines of codes

and this is because you are using an AutoField. you can change it like this:

import uuid
from django.db import models

class Posts(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, auto_created=True)
    # other lines of codes
Related