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

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'

当前回答

如果所有这些都失败了,并且当你试图在PyCharm“Python控制台”(或“Django控制台”)中导入时看到这个错误:

尝试重新启动控制台。

这很尴尬,但我过了一会儿才意识到我忘了这么做。

事情是这样的:

添加了一个新的应用程序,然后添加了一个最小模型,然后尝试在Python/Django控制台导入模型(PyCharm pro 2019.2)。这引发了“不声明app_label”的显式错误,因为我还没有将新应用添加到INSTALLED_APPS中。 所以,我将应用程序添加到INSTALLED_APPS,再次尝试导入,但仍然得到相同的错误。

来到这里,看了所有其他的答案,但似乎都不合适。

最后,我突然意识到,在将新应用程序添加到INSTALLED_APPS后,我还没有重新启动Python控制台。

注意:在向模块中添加新对象后,无法重新启动PyCharm Python控制台,也会导致非常混乱的ImportError: Cannot import name…

其他回答

我在测试中导入模型时遇到了这个错误,即给出这个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:也许这有点晚了,但我在其他人的答案中没有发现如何解决我的代码中的这个问题,我想分享我的解决方案。

我在使用。/manage.py shell时得到了这个 然后我不小心从根项目级目录导入

# don't do this
from project.someapp.someModule import something_using_a_model
# do this
from someapp.someModule import something_using_a_model

something_using_a_model()

在我的情况下,我能够找到一个修复程序,通过查看其他人的代码,它可能是相同的问题。我只需要添加'django.contrib。在settings.py文件中将Sites '添加到已安装应用的列表中。

希望这能帮助到一些人。这是我对编码社区的第一个贡献

对于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变量等等。

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

还要检查您的迁移是否正常工作

Python3 manage.py makemigrations
Python3 manage.py migrate