Melissa Stewart
Melissa Stewart

Reputation: 3605

AUTH_USER_MODEL refers to model '%s' that has not been installed"

I'm using a CustomUser in my model. This is the User Manager.

class UserManager(BaseUserManager):

    def create_user(self, email, username, password=None, is_staff=False, is_superuser=False, is_active=False,
                    is_bot=False, is_mobile_verified=False, is_online=True, is_logged_in=True):
        logger = logging.getLogger(__name__)
        logger.info("REGULAR user created!")
        if not email:
            raise ValueError('Email is required')
        if not username:
            raise ValueError('Username is required.')
        email = self.normalize_email(email)
        user = self.model(email=email, username=username, is_staff=is_staff, is_superuser=is_superuser,
                          is_active=is_active, is_bot=is_bot, is_mobile_verified=is_mobile_verified,
                          is_online=is_online, is_logged_in=is_logged_in)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password):
        logger = logging.getLogger(__name__)
        logger.info("SUPER user created!")
        return self.create_user(email, username, password=password, is_staff=True, is_superuser=True, is_active=True,
                                is_bot=False, is_mobile_verified=False, is_online=True, is_logged_in=True)

This is my definition of the custom user model.

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, max_length=255)
    mobile = PhoneNumberField(null=True)
    username = models.CharField(null=False, unique=True, max_length=255)
    full_name = models.CharField(max_length=255, blank=True, null=True)
    birthday = models.DateField(null=True)
    gender = models.CharField(max_length=255, null=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    is_mobile_verified = models.BooleanField(default=False)
    is_online = models.BooleanField(default=False)
    is_logged_in = models.BooleanField(default=True)
    is_bot = models.BooleanField(default=False)
    location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    #objects = UserManager()

    get_user_model().objects.create_user(...)

If I uncomment the line objects = UserManager() then I can run the server but the super users created from the admin backend can't log in. If I use get_user_model() the code breaks and I get the following error

 "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'bouncer.User' that has not been installed

But in my settings.py I've define auth user model

AUTH_USER_MODEL = 'bouncer.User'

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
)

What am I doing wrong here?

Upvotes: 9

Views: 18315

Answers (10)

Joshua
Joshua

Reputation: 314

I'm aware this is an old question but I struggled with this issue for two days before finding my mistake, which was failing to follow the models organization in the Django Models docs.

I would have just commented on @5fec's answer, but I don't have the reputation yet. My answer is similar to his, except importing the model in models/__init__.py worked for me. I had neglected the __init__.py file entirely.

If you have the AUTH_USER_MODEL = <app_name>.<user_model> correctly written, and you have your '<app_name>', in your INSTALLED_APPS list, but you're still getting this error, it's possible that your <custom_user> model (e.g. User) is in the wrong place.

It needs to be defined in either:

  • <app_name>.models.py

OR

  • <app_name>/models/<arbitrary_name>.py AND there is an <app_name>/models/__init__.py that contains the line from .<arbitrary_name> import <custom_user>

Upvotes: -1

silverduck
silverduck

Reputation: 469

For some reason the import from django.contrib.auth.backends import BaseBackend caused this problem. I suspect that BaseBackend tries to use the user model, but can't because it's defined further down the file. However if you define your model BEFORE that import then it'll work just fine.

Upvotes: -1

5fec
5fec

Reputation: 568

For me this was because I had myapp/models/__init__.py and I tried putting the custom User model definition in myapp/models/user.py, and setting AUTH_USER_MODEL = myapp.User. Moving the custom User model definition into myapp/models/__init__.py fixed it. I was unable to import it in __init__.py; I had to move the definition there.

Upvotes: 3

Turosik
Turosik

Reputation: 34

Never put custom user model and additional models containing links to user model in one models.py file in one app. This can be a matter of that error.

Bad idea leading to that error:

# customUserModel/models.py
from django.contrib.auth.models import AbstractUser
from django.conf import settings

class User(AbstractUser):
    pass

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    some_field = models.CharField(max_length=25)

This is a good idea:

# customUserModel/models.py
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

# additionalUserProfile/models.py
from django.conf import settings
class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    some_field = models.CharField(max_length=25)

#settings.py
AUTH_USER_MODEL = 'customUserModel.User'

Upvotes: 0

Wardee
Wardee

Reputation: 41

In my case I accidentally pasted in Meta class of my custom user the attribute abstract = True. So it raises this error.

Upvotes: 4

subodhk
subodhk

Reputation: 254

Try shifting the position of the bouncer app in your INSTALLED APPS, this worked for me.

Upvotes: -1

Heartthrob_Rob
Heartthrob_Rob

Reputation: 378

For anyone reading this in 2020, I suspect the problem is dependency related. I ran into the same error as OP.

Your first two checks should be:

1 - Is the app in the installed apps list in your settings.py?

2 - Is the AUTH_USER_MODEL = "app_name_from_apps_py.model_name" set in settings.py?

This was as far as most of the other responses I read go.

What I didn't realise on reading the docs is that to use get_user_model() you need to have established your model first. Of course, right?!

So above, where OP is using get_user_model(), they are creating a circular dependency. You cannot use get_user_model() within the class that creates this model.

Upvotes: 15

GeorgiySurkov
GeorgiySurkov

Reputation: 19

Make sure that you register your model in admin.py and not in models.py

# admin.py
from django.contrib.auth.admin import UserAdmin

admin.site.register(YourUser, UserAdmin)

This solved the problem for me.

Upvotes: 0

yonatan
yonatan

Reputation: 615

try importing from django.db import models only after importing from django.contrib.auth.models import AbstractUser

Upvotes: -2

AKX
AKX

Reputation: 168824

That error looks like bouncer isn't in your INSTALLED_APPS.

So to clarify, you have to have

  • bouncer/models.py that contains the User model (or models/__init__.py which imports the model from another file)
  • 'bouncer' in the INSTALLED_APPS list in the settings
  • AUTH_USER_MODEL = 'bouncer.User' (as you do).

Upvotes: 5

Related Questions