Search code examples
pythondjangodjango-modelsdjango-formsweb-frameworks

In Django, when I run migrate I get the error : accounts_userinfo.user_id may not be NULL


Whenever I run python manage.py migrate accounts I get the error code : django.db.utils.IntegrityError: accounts_userinfo.user_id may not be NULL

I believe this is caused by me linking a model with more user information, with the django user model. This is my models.py

class UserInfo(models.Model):
    c_name = models.CharField(max_length=120)
    c_site = models.CharField(max_length=120)
    link = models.ForeignKey(User)

Does anybody see an obvious problem that I may be missing? Let me know if you need any more code. Thanks much. -Ramsey


Solution

  • Foreign keys cannot be null by default. You either need to make it nullable:

    class UserInfo(models.Model):
        c_name = models.CharField(max_length=120)
        c_site = models.CharField(max_length=120)
        link = models.ForeignKey(User, null = True)
    

    Or set a default:

    class UserInfo(models.Model):
        c_name = models.CharField(max_length=120)
        c_site = models.CharField(max_length=120)
        link = models.ForeignKey(User, default = some_id)
    

    This will depend if the link is required. It appears that is likely is required.

    This happens because there is existing data in the database that does not have a value for this field (link) and Django cannot guess. Another option is to remove all entries in the Users and UserInfo tables (assuming the data is not in production) and then migrate.

    If you're just trying to make it work, you can set the default to one of the existing user models, then go into the Django admin panel and correct the entries. The problem with this is that you will have to specify an ID (ie. 1) which may not be present on other databases. But again, if this is still in development and no real data is being migrated, then you're fine.

    The last option is to set it as nullable at first, then go into the data, create entries for everything, and then create another migration to remove the nullable attribute.