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

西门·鲁斯尼斯

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

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

RuntimeError: Model class myproject.myapp.models.MyModel doesn't declare an explicit app_label and isn't in an application in 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.

settings.py:

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

apps.py:

from django.apps import AppConfig


class MyAppConfig(AppConfig):
    name = 'myapp'

tests.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

models.py:

from django.db import models


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

    def __str__(self):
        return self.name
西门·鲁斯尼斯

该问题是由于将a__init__.py放置在django项目的根文件夹中引起的。通过删除此文件,它已解决。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章