RuntimeError:模型类 myapp.models.class 未声明显式 app_label 并且不在 INSTALLED_APPS 中的应用程序中

Posted

技术标签:

【中文标题】RuntimeError:模型类 myapp.models.class 未声明显式 app_label 并且不在 INSTALLED_APPS 中的应用程序中【英文标题】:RuntimeError: Model class myapp.models.class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS 【发布时间】:2020-08-13 22:11:27 【问题描述】:

这个错误已经解决了很多次,但似乎没有一个答案适用于我。 我对 Python 2 和 3 相当有经验。我第一次使用 django。我开始制作一个项目。当我使用基本数据库时,在我第一次调用 class.objects 后,标题错误发生了。在尝试修复它一段时间后,我转向了 django 教程,我决定一步一步地做所有事情。在使用渲染之前,该错误再次发生在“编写你的第一个 Django 应用程序,第 3 部分”。

目录:

\home_dir
   \lib
   \Scripts
   \src
      \.idea
      \pages
      \polls
         \migrations
         __init__.py
         admin.py
         apps.py
         models.py
         test.py
         views.py
      \templates
      \django_proj
         __init__.py
         asgi.py
         manage.py
         settings.py
         urls.py
         wsgi.py
      __init__.py
      db.sqlite3
      manage.py

不要打扰页面它是一个测试应用程序。

django_proj\settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    # My App
    'polls'
    'pages'
]

模板和数据库配置良好

投票\apps.py:

from django.apps import AppConfig


class PollsConfig(AppConfig):
    name = 'polls'

polls\models.py

from django.db import models
from django.utils import timezone
import datetime


# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    published_date = models.DateTimeField('date published')
    objects = models.Manager()

    def __str__(self):
        return self.question_text

    def was_pub_recently(self):
        return self.published_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    vote = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

polls\views.py

from django.shortcuts import render
from django.http import HttpResponse
from src.polls.models import Question
from django.template import loader


# Create your views here.
def index(request, *args, **kwargs):
    latest_question_list = Question.objects.order_by('-published_date'[:5])
    template = loader.get_template('polls/index.html')
    context = 
        'latest_question_list': latest_question_list
    
    return HttpResponse(template.render(context, request))


def details(request, question_id, *args, **kwargs):
    return HttpResponse(f"Question: question_id")


def results(request, question_id, *args, **kwargs):
    response = f"Results for question question_id"
    return HttpResponse(response)


def vote(request, question_id, *args, **kwargs):
    return HttpResponse(f"Vote on question question_id")

django_proj\urls.py

from django.contrib import admin
from django.urls import include, path

from src.pages.views import home_view, base_view, context_view
from src.polls.views import index, details, results, vote

urlpatterns = [
    path('', home_view, name='home'),
    path('admin/', admin.site.urls),
    path('base/', base_view, name='base'),
    path('context/', context_view, name="context"),
    # Polls
    path('home/', index, name='index'),
    path('<int:question_id>/', details, name='details'),
    path('<int:question_id>/results/', results, name='results'),
    path('<int:question_id>/vote/', vote, name='vote'),
]

错误:

Traceback (most recent call last):
  File "c:\users\panos\appdata\local\programs\python\python37-32\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "c:\users\panos\appdata\local\programs\python\python37-32\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\core\management\base.py", line 395, in check
    include_deployment_checks=include_deployment_checks,
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
    return checks.run_checks(**kwargs)
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
    return check_method()
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\urls\resolvers.py", line 407, in check
    for pattern in self.url_patterns:
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module
    return import_module(self.urlconf_name)
  File "c:\users\panos\appdata\local\programs\python\python37-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\panos\Dev\cfehome\src\testdjango\urls.py", line 20, in <module>
    from src.polls.views import index, details, results, vote
  File "C:\Users\panos\Dev\cfehome\src\polls\views.py", line 3, in <module>
    from .models import Question
  File "C:\Users\panos\Dev\cfehome\src\polls\models.py", line 7, in <module>
    class Question(models.Model):
  File "C:\Users\panos\Dev\cfehome\lib\site-packages\django\db\models\base.py", line 115, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class src.polls.models.Question doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

Python 3.7 版

Django 版本 3.0.4

我已经试过了:

https://medium.com/@michal.bock/fix-weird-exceptions-when-running-django-tests-f58def71b59a

Django model "doesn't declare an explicit app_label"

还有其他两个解决方案,但我没有链接

在尝试修复此问题 12 小时后,我猜测这是兼容性问题或我的导入和 init 文件确实有问题。

编辑。 好像是我的错。对于所有遇到相同错误的人,首先确保您将您的应用程序放入 INSTALLED_APPS,然后按照 django 文档的建议,您目录中的所有文件都已妥善存档(如果您选择以不同的方式制作它们,请确保您还修复了导入因此)。也不要在你的名字中使用 django、test 等词,因为 django 的搜索者可能会遇到它们并覆盖重要的 django 函数。

【问题讨论】:

【参考方案1】:

您在 django_proj\settings.py 中的 INSTALLED_APPS 列表不正确。列表中的每个项目都应该用逗号分隔。尝试如下更新您的列表。

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
# My App
'polls',
'pages',]

【讨论】:

是的,起初这似乎是错误,但在我在那里添加昏迷后我也遇到了同样的错误。我发现我的导入不一致,我的目录很乱。谢天谢地,我已经离开了。无论如何感谢您的回答。

以上是关于RuntimeError:模型类 myapp.models.class 未声明显式 app_label 并且不在 INSTALLED_APPS 中的应用程序中的主要内容,如果未能解决你的问题,请参考以下文章

RuntimeError:模型类 xxx.xxx 未声明显式 app_label 且不在 INSTALLED_APPS 中的应用程序中

RuntimeError:模型类 myapp.models.class 未声明显式 app_label 并且不在 INSTALLED_APPS 中的应用程序中

RuntimeError:模型类 django.contrib.sites.models.Site 未声明显式 app_label 且不在 INSTALLED_APPS 中的应用程序中

在阅读器中定义映射

PyTorch:RuntimeError:输入、输出和索引必须在当前设备上

RuntimeError:CUDA 错误:触发了设备端断言 - BART 模型