Django 启动项目服务的时候可能会报以下错误:以下Apps.userPage是应用名,换成你自己的!

单项目不太可能会遇到这个问题,一般多应用放在一个Apps下时可能会出现.doesn’t declare an explicit app_label and isn’t in an application in INSTALLED_APPS

  File "D:\Fineex WorkSpace\DatasPlat\Apps\userPage\urls.py", line 18, in <module>
    from . import views
  File "D:\Fineex WorkSpace\DatasPlat\Apps\userPage\views.py", line 6, in <module>
    from . import models
  File "D:\Fineex WorkSpace\DatasPlat\Apps\userPage\models.py", line 6, in <module>
    class Department(models.Model):
  File "D:\Fineex WorkSpace\DatasPlat\venv\lib\site-packages\django\db\models\base.py", line 113, in __new__
    raise RuntimeError(
RuntimeError: Model class Apps.userPage.models.Department doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

如果你确信在models.py中正确添加了对应的Model:

class Department(models.Model):
    code = models.CharField(max_length=64, blank=False, null=False, primary_key=True, unique=True)
    name = models.CharField(max_length=128, blank=False, null=False)
    pcode = models.CharField(max_length=64)
    desc = models.CharField(max_length=255, blank=True, null=True)
    lever= models.IntegerField(blank=False, null=False)
    class Meta:
        db_table = 'department'
        verbose_name_plural = db_table

如果你确信在settings.py中已正确注册App

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

且在Apps/userPage/view.py中按照正确路径(一般为相对路径)

from . import models

如果你觉得不应该报错,甚至你Apps下面的其它App没有这个错误,或者删除上面的引入都可以正常启动项目的话,错误大概率出险在Apps/userPage/apps.py的AppConfig类中,

class UserpageConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'userPage' # 出错点在这里

改成

class UserpageConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'Apps.userPage' 

或者直接在apps.py中删掉这个Config,再次启动这个项目,已成功!

只是Django项目启动报错的一种情况,不一定适用于其它类型,先判断好。

原文链接:Django报错之…doesn’t declare an explicit app_label… - 乐忘尘 - 博客园 (cnblogs.com)