You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django 2.2执行命令时ContentType模型报错,求解决方案

Django 2.2 报错排查:ContentType 未声明 app_label 且不在 INSTALLED_APPS 中

问题详情

使用Django 2.2版本,执行以下命令时触发报错:

python3.7 manage.py collectstatic 
python3.7 manage.py shell 
python3.7 manage.py runserver

报错信息:

Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS

当前INSTALLED_APPS配置:

INSTALLED_APPS = (
    'actions.apps.MyAppConfig',
    'common.apps.MyAppConfig',
    'hotels.apps.MyAppConfig',
    'extranet.apps.MyAppConfig',
    'communication.apps.MyAppConfig',
    'bulk_uploader.apps.MyAppConfig',
    'registration.apps.MyAppConfig',
    'channel_manager.apps.MyAppConfig',
    'reports.apps.MyAppConfig',
    'mobile.apps.MyAppConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'admin_shortcuts',
    'guardian',
    'actstream',
    'rest_framework',
    'django_filters',
    'rest_framework.authtoken',
    'oauth2app',
    'ckeditor',
    'stats',
    'django_celery_beat',
)

解决建议

  • 修复自定义AppConfig命名冲突:所有自定义应用都使用MyAppConfig作为配置类名,会导致Django无法区分不同应用,引发加载混乱。每个应用的apps.py中需定义唯一的配置类,比如actions应用的apps.py改为:
    from django.apps import AppConfig
    
    class ActionsConfig(AppConfig):
        name = 'actions'
    
    然后在INSTALLED_APPS中更新为'actions.apps.ActionsConfig',其余应用同理修改为对应名称的Config类。
  • 调整INSTALLED_APPS加载顺序:将Django自带的django.contrib系列应用移到自定义应用之前,确保核心应用优先加载:
    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'actions.apps.ActionsConfig',
        'common.apps.CommonConfig',
        # 其余自定义应用...
    )
    
  • 清理缓存并重启:手动删除项目根目录和各应用目录下的__pycache__文件夹,或执行python3.7 manage.py clearcache(Django 2.2+支持),之后重新运行命令。
  • 检查自定义代码中的ContentType引用:确保所有导入ContentType的代码路径正确(from django.contrib.contenttypes.models import ContentType),且未在未注册到INSTALLED_APPS的模块中使用该模型。

内容的提问来源于stack exchange,提问作者user3289040

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:45:45