gpt4 book ai didi

python - 无法在 Django 3 中导入测试模块

转载 作者:行者123 更新时间:2023-12-05 08:38:24 25 4
gpt4 key购买 nike

我正尝试按照 Django 文档中的描述为我的应用程序运行测试:https://docs.djangoproject.com/en/3.0/intro/tutorial05/

但是,对于我在下面显示的最小示例,我收到一条错误消息:

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

我是否需要进行一些额外的配置才能运行测试,或者我可能犯了或忘记了其他一些错误?

完整堆栈跟踪:

$ ./manage.py test myapp


System check identified no issues (0 silenced).
E
======================================================================
ERROR: myproject.myapp.tests (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: myproject.myapp.tests
Traceback (most recent call last):
File "/usr/lib64/python3.8/unittest/loader.py", line 436, in _find_test_path
module = self._get_module_from_name(name)
File "/usr/lib64/python3.8/unittest/loader.py", line 377, in _get_module_from_name
__import__(name)
File "/home/simernes/workspace/myproject/myapp/tests.py", line 2, in <module>
from .models import MyModel
File "/home/simernes/workspace/myproject/myapp/models.py", line 5, in <module>
class MyModel(models.Model):
File "/home/simernes/workspace/myproject/env/lib/python3.8/site-packages/django/db/models/base.py", line 112, in __new__
raise RuntimeError(
RuntimeError: Model class myproject.myapp.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

设置.py:

INSTALLED_APPS = [
'myapp.apps.MyAppConfig',
...
]

应用程序.py:

from django.apps import AppConfig


class MyAppConfig(AppConfig):
name = 'myapp'

测试.py:

from django.test import TestCase
from .models import MyModel


# Create your tests here.
class MyModelTests(TestCase):

def model_names_are_unique(self):
"""
The database crashes if the same name is registered twice
:return:
"""
unique_name = "Unique Name"

model_first = MyModel(name=unique_identifier)
model_first.save()

model_second = MyModel(name=unique_identifier)
model_second.save()
self.assertTrue(True) # todo: assert that an error is raised

模型.py:

from django.db import models


class MyModel(models.Model):
name = models.CharField(max_length=255, unique=True)

def __str__(self):
return self.name

最佳答案

这个问题是由于 __init__.py 以某种方式被放置在 django 项目的根文件夹中引起的。删除这个文件就解决了。

关于python - 无法在 Django 3 中导入测试模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62793733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com