我真是一筹莫及。经过十几个小时的故障排除,可能更多,我以为我终于可以做生意了,但接着我发现:

Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label 

网上关于这方面的信息太少了,没有解决方案可以解决我的问题。任何建议都将不胜感激。

我使用的是Python 3.4和Django 1.10。

从我的settings.py:

INSTALLED_APPS = [
    'DeleteNote.apps.DeletenoteConfig',
    'LibrarySync.apps.LibrarysyncConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

我的app .py文件是这样的:

from django.apps import AppConfig


class DeletenoteConfig(AppConfig):
    name = 'DeleteNote'

and

from django.apps import AppConfig


class LibrarysyncConfig(AppConfig):
    name = 'LibrarySync'

当前回答

我今天试图运行Django测试时出现了这个错误,因为我在其中一个文件中使用了.models import *语法的简写。问题是我的文件结构是这样的:

    apps/
      myapp/
        models/
          __init__.py
          foo.py
          bar.py

在models/__init__.py中,我使用简写语法导入我的模型:

    from .foo import *
    from .bar import *

在我的应用程序中,我像这样导入模型:

    from myapp.models import Foo, Bar

这导致Django模型在运行./manage.py测试时没有显式声明app_label。

为了解决这个问题,我必须显式地从models/__init__.py中的完整路径导入:

    from myapp.models.foo import *
    from myapp.models.bar import *

这就解决了错误。

H - t https://medium.com/@michal。博克fix-weird-exceptions-when-running-django-tests-f58def71b59a

其他回答

我在测试中导入模型时遇到了这个错误,即给出这个Django项目结构:

|-- myproject
    |-- manage.py
    |-- myproject
    |-- myapp
        |-- models.py  # defines model: MyModel
        |-- tests
            |-- test_models.py

在文件test_models.py中导入MyModel:

from models import MyModel

如果以这种方式导入,问题就解决了:

from myapp.models import MyModel

希望这能有所帮助!

PS:也许这有点晚了,但我在其他人的答案中没有发现如何解决我的代码中的这个问题,我想分享我的解决方案。

对于PyCharm用户:我有一个错误使用不“干净”的项目结构。

Was:

project_root_directory
└── src
    ├── chat
    │   ├── migrations
    │   └── templates
    ├── django_channels
    └── templates

Now:

project_root_directory
├── chat
│   ├── migrations
│   └── templates
│       └── chat
├── django_channels
└── templates

这里有很多好的解决方案,但我认为,首先,你应该清理你的项目结构或调优PyCharm Django设置之前,设置DJANGO_SETTINGS_MODULE变量等等。

希望它能帮助到别人。欢呼。

我在Django rest_framework中构建API时遇到了类似的错误。

模型类apps.core.models.University没有显式声明> app_label,也不在INSTALLED_APPS中的应用程序中。

Luke_aus的回答纠正了我的urls.py

from

from project.apps.views import SurgeryView

to

from apps.views import SurgeryView

我刚才也遇到了同样的问题。我已经通过在应用程序名称上添加一个名称空间来修复我的。希望有人觉得这有帮助。

apps.py

from django.apps import AppConfig    

class SalesClientConfig(AppConfig):
        name = 'portal.sales_client'
        verbose_name = 'Sales Client'

如果所有配置都是正确的,导入时可能会一团糟。注意您是如何导入有问题的模型的。

下面的代码在.models import Business中不起作用。请使用完全导入路径:from myapp。模型进口业务