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

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项目结构:

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

其他回答

很可能您有依赖的导入。

在我的例子中,我在我的模型中使用了一个序列化器类作为参数,并且序列化器类使用了这个模型: serializer_class = AccountSerializer

from ..api.serializers import AccountSerializer

class Account(AbstractBaseUser):
    serializer_class = AccountSerializer
    ...

在“serializers”文件中:

from ..models import Account

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = (
            'id', 'email', 'date_created', 'date_modified',
            'firstname', 'lastname', 'password', 'confirm_password')
    ...

在我移动SECRET_KEY以从环境变量中提取,并且在运行应用程序时忘记设置它之后,我收到了这个错误。如果你的settings。py中有这样的东西

SECRET_KEY = os.getenv('SECRET_KEY')

然后确保您实际上设置了环境变量。

对于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中的manage.py和init.py在同一个目录下。

之前:

|-- myproject
  |-- __init__.py  <---
  |-- manage.py
  |-- myproject
    |-- ...
  |-- app1
    |-- models.py
  |-- app2
    |-- models.py

后:

|-- myproject
  |-- manage.py
  |-- myproject
    |-- ...
  |-- app1
    |-- models.py
  |-- app2
    |-- models.py

当你得到这个“没有声明一个显式的app_label”错误时,你会感到非常困惑。但是删除这个init文件解决了我的问题。

问题是:

您已经对模型文件进行了修改,但尚未将其添加到DB,但您正在尝试运行Python manage.py runserver。 运行Python manage.py makemigrations Python manage.py迁移 现在Python manage.py runserver,一切都应该没问题了。