【问题标题】:RuntimeError: Model doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPSRuntimeError:模型未声明显式 app_label 并且不在 INSTALLED_APPS 中的应用程序中
【发布时间】:2023-02-18 20:34:47
【问题描述】:

我正在用 Django 编写一个应用程序,我正在尝试进行一些单元测试 但我似乎找不到测试失败的原因 那是测试页:

import re
from django.test import TestCase
from django.urls import reverse
from . import models



class BasicTests(TestCase):

    def test_firstname(self):
        print('test11')
        acc = models.Accounts()
        acc.first_name = 'Moran'
        self.assertTrue(len(acc.id) <= 9, 'Check name is less than 50 digits long')
        self.assertFalse(len(acc.id) > 50, 'Check name is less than 50 digits long')

我得到的错误是:

RuntimeError:模型类 DoggieSitter.accounts.models.Accounts 未声明显式 app_label 且不在应用程序中 INSTALLED_APPS

那是我安装的应用程序:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts'
]

【问题讨论】:

  • 根据错误,看起来安装的应用程序应该是DoggieSitter.accounts。您如何运行测试以及从哪里运行?
  • 我正在从终端运行命令“python manage.py test”
  • 您是否尝试过将 DoggieSitter.accounts 添加到您的 INSTALLED_APPS 设置而不是 accounts
  • 是的,我做到了,但有一个错误“ModuleNotFoundError:没有名为‘Dog Sitter’的模块”此外,我无法上传网站添加更多与测试无关的问题
  • 你好@ShTurj 尝试添加完整的应用程序位置,例如。(accounts.apps.AccountsConfig)在你的 INSTALLED_APPS 里面

标签: django django-models django-testing django-settings django-tests


【解决方案1】:

TLDR;:尝试将上面的第 4 行更改为显式导入,例如 from DoggieSitter.accounts import models

每当运行 tests.py 具有诸如 from .models import ModelName 的相对导入的测试时,我都会遇到这个问题。搜索了大约一个小时后,我偶然发现了this answer to exactly the tutorial I was following

就我而言,我正在尝试from .models import Recipe。我的项目结构如下,所以我改成from apps.recipes.models import Recipe,现在测试运行正常。

src
├── __init__.py
├── apps
│   ├── accounts
│   ├── core
│   └── recipes
├── config
│   ├── __init__.py
│   ├── admin.py
│   ├── asgi.py
│   ├── db.sqlite3
│   ├── secrets
│   ├── settings
│   │   ├── __init__.py
│   │   ├── base
│   │   └── development
│   ├── tests.py
│   ├── urls.py
│   ├── utilities.py
│   └── wsgi.py
├── manage.py
├── static
└── templates

【讨论】:

    猜你喜欢
    • 2020-08-13
    • 2018-12-29
    • 2019-08-28
    • 2016-05-25
    • 2020-05-16
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    相关资源
    最近更新 更多