RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS

RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS

我正在使用 Django Rest Framework 和 AngularJs 构建应用程序。我正在使用 Django-rest-auth 进行身份验证,但我无法设置它。无论如何,我正在尝试设置此 app with my project. I realized I need to install django-rest-auth-registration to get it running, so I followed this documentation 以执行以下操作:

我运行命令

pip install django-rest-auth

pip install django-allauth

我的任何 settings.py 看起来像这样:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 3rd party apps
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'allauth',
    'allauth.account',
    'rest_auth.registration',

    # My app
    'myapp',
]

我还添加了身份验证后端 context_processors 和正确的 url。

但是,当我尝试迁移时,我的终端抛出以下错误:

RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

为什么会出现此错误,如何解决以迁移我的项目?谢谢!

修正

只需将 Django 的 Sites framework 添加到您的应用程序并在您的设置中将 SITE_ID 设置为 1。

INSTALLED_APPS = [
    ...
    'django.contrib.sites',
]

SITE_ID = 1

为什么会这样?

Django's Sites Framework is a contributed module bundled with the core library that allows for the use of a single Django application/codebase with different sites (that can use different databases, logic in views, etc). The SITE_ID setting,如文档中所述,“ 用于使应用程序数据可以连接到特定站点,并且单个数据库可以管理多个站点的内容。 “

在这种特殊情况下 AllAuth requires the Sites Framework 才能正常运行。许多其他第三方库的构建是为了安全地处理可能存在多个站点的情况,因此可能是最好的。

我通过 Google 搜索找到了这个 post。我的问题是 运行 测试因错误而爆炸:

RuntimeError: Model class app.taxonomy.models.Term doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

这是 运行 在 Python 2.7.x 上的绝对导入。正如 Colton Hicks 在下面的评论中提到的,Python 3(pytest 3.2.3 和 Django 1.11.4)也可能发生这种情况。

在我的 tests.py:

from __future__ import absolute_import
[...]
from .models import Demographics, Term

将相对导入更改为绝对导入后,问题消失了:

from taxonomy.models import Demographics, Term

HTH

我遇到了上面的错误。但是我的问题是 urls.py。我正在关注 PyDanny cookiecutter django 食谱。我的错误是在 urls.py 中加入了这一行:

    url(r'^demo/', include('project.demoapp.urls', namespace='demoapp')),

当我对此进行更正时:

    url(r'^demo/', include('demoapp.urls', namespace='demoapp')),

一切顺利。我还更改了我的本地应用程序(我首先这样做,所以严重错误是 url 配置错误):

LOCAL_APPS = [
    # Your stuff: custom apps go here
    'demoapp.apps.DemoAppConfig',
]

只需将 'django.contrib.sites', 添加到 INSTALLED_APPS 并在 settings.py 文件中设置 SITE_ID = 1

尝试在模型 Meta class 中添加 app_label = 'yourApp':

class Meta:

    app_label = 'yourApp'

我安装了 django 调试工具栏,这实际上导致了 the/my 问题。 INSTALLED_APPS(在 settings.py 中)需要条目 'django.contrib.sessions'。添加后确保运行迁移。