Django 1.8 LookupError: 模型未注册AUTH_USER_MODEL。

4

Django 1.8和Python 3.4

我在我的应用程序authenticateclients中使用了一个称为UploaderClient的自定义用户模型。当我运行checkmakemigrationsmigrate时,会出现LookupError: Model 'authenticateclients.UploaderClient' not registered.错误。请帮助我。

在settings.py文件中,我将AUTH_USER_MODEL定义为authenticateclients.UploaderClient

authenticateclients/models.py

    from django.db import models
    from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

    # Create your models here.

   class UploaderClientManager(BaseUserManager):
       def create_user(self, accountname, password=None, **kwargs):
           if not accountname:
               raise ValueError('Users must have a valid accountname.')

           if not kwargs.get('email'):
               raise ValueError('Users must have a valid email.')

           if not kwargs.get('company_name'):
               raise ValueError('Users must have a valid company name.')

           account = self.model(
               accountname=self.normalize_accountname(accountname),email=kwargs.get('email'), company_name=kwargs.get('company_name')
           )

           account.set_password(password)
           account.save()

           return account

       def create_superuser(self, accountname, password, **kwargs):
           account = self.create_user(accountname, password, **kwargs)

           account.is_admin = True
           account.save()

           return account


   class UploaderClient(AbstractBaseUser):
       email = models.EmailField()
       accountname = models.CharField(max_length=100, unique=True)
       company_name = models.CharField(max_length=100)
       vuforiadb_name = models.CharField(max_length=100, blank=True)

       is_admin = models.BooleanField(default=False)

       created_at = models.DateTimeField(auto_now_add=True)
       updated_at = models.DateTimeField(auto_now=True)

       objects = UploaderClientManager()

       USERNAME_FIELD = 'accountname'
       REQUIRED_FIELDS = ['email','company_name']

       def __unicode__(self):
           return self.accountname

       def get_company_name(self):
           return self.company_name

       def get_vuforiadb_name(self):
           return self.vuforiadb_name

settings.py

"""
Django settings for ARPixelSite project.

Generated by 'django-admin startproject' using Django 1.8.6.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# -*- coding: utf-8 -*-
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

gettext = lambda s: s

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@-$h5gh5%s$70hd=ii55it!+4@a*u8b(c8aqumqkx@*m8%v89l'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'djangocms_admin_style',  # for the admin skin. You **must** add 'djangocms_admin_style' in the list **before** 'django.contrib.admin'.
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'cms',  # django CMS itself
    'treebeard',  # utilities for implementing a tree
    'menus',  # helper for model independent hierarchical website navigation
    #'south',  # Only needed for Django < 1.7
    'sekizai',  # for javascript and css management
    'djangocms_file',
    'djangocms_flash',
    'djangocms_googlemap',
    'djangocms_inherit',
    'djangocms_picture',
    'djangocms_teaser',
    'djangocms_video',
    'djangocms_link',
    'djangocms_snippet',
    'rest_framework',
    'clientupload',
    'authenticateclients',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'cms.middleware.user.CurrentUserMiddleware',
    'cms.middleware.page.CurrentPageMiddleware',
    'cms.middleware.toolbar.ToolbarMiddleware',
    'cms.middleware.language.LanguageCookieMiddleware',
)

ROOT_URLCONF = 'ARPixelSite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.core.context_processors.i18n',
                'django.core.context_processors.request',
                'django.core.context_processors.media',
                'django.core.context_processors.static',
                'sekizai.context_processors.sekizai',
                'cms.context_processors.cms_settings',
            ],
        },
    },
]

WSGI_APPLICATION = 'ARPixelSite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'ARPixelDB',
        'USER': 'djangouser',
        'PASSWORD': 'djangouser',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
    )
}

"""
TEMPLATE_DIRS = (
    # The docs say it should be absolute path: BASE_DIR is precisely one.
    # Life is wonderful!
    os.path.join(BASE_DIR, "templates"),
)
"""

CMS_TEMPLATES = (
    ('template_1.html', 'Template One'),
    ('template_2.html', 'Template Two'),
)

LANGUAGES = [
    ('en', 'English'),
]

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

SITE_ID = 1

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"

CMS_PAGE_MEDIA_PATH = os.path.join(MEDIA_ROOT, "cms_page_media")

AUTH_USER_MODEL = 'authenticateclients.UploaderClient'

当我运行checkmakemigrationsmigrate时,我会收到以下错误提示:
/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/importlib/_bootstrap.py:321: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9.
  return f(*args, **kwds)

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
    utility.execute()
  File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/core/management/__init__.py", line 328, in execute
    django.setup()
  File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/cms/models/__init__.py", line 4, in <module>
    from .permissionmodels import *  # nopyflakes
  File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/cms/models/permissionmodels.py", line 29, in <module>
    User = apps.get_registered_model(user_app_name, user_model_name)
  File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/apps/registry.py", line 266, in get_registered_model
    "Model '%s.%s' not registered." % (app_label, model_name))
LookupError: Model 'authenticateclients.UploaderClient' not registered.

所以我的做法是注释掉这行代码。
AUTH_USER_MODEL = 'authenticateclients.UploaderClient'

运行makemigrationsmigrate命令。 迁移已应用。 然后取消上述行的注释并尝试checkmakemigrationsmigrate时,仍然会出现相同的错误。

请帮忙解决这个错误。 如果无法修复,我可以通过注释掉该行继续进行我的项目吗?还是如果我省略该行,身份验证将无法工作。


当你注释掉CMS工作时,因为获取权限是问题的原因。而获取权限是在CMS应用程序上进行的。 - dani herrera
部分地解决方案是在INSTALLED_APPS中注释掉djangocms和其他相关应用程序。我成功执行了 makemigrationsmigrate。但是如果我取消对cms的注释并尝试checkmakemigrationsmigrate,我会遇到同样的错误。所以我无法使用djangocms应用程序... 有谁能指导一下如何同时使用自定义身份验证和django-cms? - rasalghul
你的代码中可能有一些在自定义认证注册之前使用CMS内容的东西,我通常遵循以下步骤:1)将自定义用户模型放在其应用程序中,并仅包含该类;2)将导入CMS库的所有内容从model.py包中移出;3)在INSTALLED_APPS中的所有内容之前导入自定义认证,并在本地应用程序之前将CMS作为最后一件事导入。 - simone cittadini
3个回答

10

针对这个具体的问题,@danihp 已经指出了问题的一部分。您需要在 INSTALLED_APPS 中将带有自定义模型的应用程序放置在 "cms" 之前。

INSTALLED_APPS = {
    'your_custom_app',
    '...',
    'cms',
}

传说。谢谢! - JDavies
请问您能否详细说明一下您的答案是如何运作的以及为什么有效呢? - Moad Ennagi
为了补充上面的答案,我还必须确保我的cms包导入在models.py中的auth用户模型之后。 - Display name

0

从您的错误堆栈跟踪来看,似乎存在获取权限的问题:

File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/cms/models/permissionmodels.py", line 29, in User = apps.get_registered_model(user_app_name, user_model_name)

Django文档在Django中自定义身份验证解释道:

如果您不包括PermissionsMixin,则必须确保不在ModelBackend上调用权限方法。 ModelBackend假定您的用户模型上可用某些字段。 如果您的User模型不提供这些字段,则在检查权限时会收到数据库错误。

因此,对于您的情况,避免错误的简单方法是继承PermissionsMixin

这是一个抽象模型,您可以将其包含在User模型的类层次结构中,从而获得支持Django权限模型所需的所有方法和数据库字段。

对于您的代码:

class UploaderClient(AbstractBaseUser, PermissionsMixin):
    ...

这个不起作用...我甚至尝试了以下步骤:1)将我的authenticateclients/models.py更改为来自此问题https://dev59.com/PYrda4cB1Zd3GeqPSer9fowl/models.py模型。然后我更改了AUTH_USER_MODEL ='authenticateclients.User'。我仍然收到相同的模型未注册错误。 - rasalghul
谢谢回答。我会尝试上面的方法。但如果您能对我的答案进行一些解释,那将非常有帮助。问题可能就出在那里。 - rasalghul

0
这个问题是LookupError: Model '' not registered.首要结果,所以我在这里加上:

对于那些在开发环境中使用sqlite3数据库安装一些应用程序的人,你可以简单地删除默认的project.db文件(如果你没有丢失任何东西的话)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接