The field items.Item.owner was declared with a lazy reference to 'items.user', but app 'items' doesn't provide model 'user'

Viewed 139

I have extended User Django model using AbstractUser and I have pointed AUTH_USER_MODEL = 'items.User' in my settings/base.py, then I repointed all the FK to 'items.User'( was User before the change), but I am getting this error in every class I have mentioned 'items.User' when I run python manage.py migrate

Approach 1

======items/models.py=======
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
    bio = models.TextField(max_length=500, null=True, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    address = models.CharField(max_length=100,null=True, blank=True)
-----------------------------------------------
======core/settings/base.py=======
....
ALLOWED_HOSTS = []
AUTH_USER_MODEL = 'items.User'
....
-----------------------------------------------
=====contracts/models.py=======

class Contract(models.Model):
    .......
    owner = models.ForeignKey('items.User', on_delete=models.CASCADE)
    .........

Approach 2 I have imported User model from core.settings.base.py

======core/settings/base.py=====
....
ALLOWED_HOSTS = []
AUTH_USER_MODEL = 'items.User'
....
-----------------------------------------------
=======contracts/model.py=====
from core.settings.base import AUTH_USER_MODEL
User = AUTH_USER_MODEL

class Contract(models.Model):
    .......
    owner = models.ForeignKey('items.User', on_delete=models.CASCADE)
    .........

and still getting the same error, do I need to drop Db or something because I kind of start to think about a conflict with migrations file with the new change(kind of circulation-alike issue)!!???

1 Answers

You used 'items.user' (with lowercase) in your Item model (not the Contact model), hence the error: it should be 'items.User' (with uppercase). But this is not how you should reference to a user. As the referencing the user model section of the documentation says, you should work with the AUTH_USER_MODEL setting, so:

from django.conf import settings

class Contract(models.Model):
    # …
    owner = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    # …

You thus do not reference core.settings.base directly, but let Django's configuration model load the settings, convert it to an immutable object, and then use the AUTH_USER_MODEL settingĀ [Django-doc] from that object. This will also fall back to the default for a given setting if you do not specify that setting.

You should do this for all models that reference the user model (so Item as well).

Related