我正按照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
答案 0 :(得分:2)
该问题是由于将__init__.py
放置在django项目的根文件夹中引起的。通过删除此文件,它已解决。
答案 1 :(得分:0)
尝试在“ settings.py”文件中进行此修改:
INSTALLED_APPS = [
...
'myapp',
]