【问题标题】:How to set app_label in test如何在测试中设置 app_label
【发布时间】:2014-11-08 20:45:04
【问题描述】:

我正在学习一个基本 Django 网页和一个应用程序的在线教程。

到目前为止,我做的第一件事也是唯一一件事是使用 sqllite 数据库创建项目和单个应用程序。

我已将应用程序正确添加到settings.py 文件中。

在应用程序models.py 中,我定义了一个模型。

makemigrations 命令已成功为模型创建数据库。

创建模型类后,我尝试编写以下测试脚本来测试模型的构造函数。此脚本位于与models.py 相同级别的应用目录中。

from django.test import TestCase
from models import Foodie # the model
import os

# Create your tests here.
class TestModel(unittest.TestCase):
    def test_foodie(self):
        tc = Foodie()

if __name__ == '__main__':  
    unittest.main()

我得到错误:

builtins.IndexError: list index out of range
File "C:\WebDev\DinnerServer\Rolls\tests.py", line 2, in <module>
from models import Foodie
File "C:\WebDev\DinnerServer\Rolls\models.py", line 7, in <module>
class Foodie(models.Model):
File "C:\Python33\Lib\site-packages\Django-1.7.1-py3.3.egg\django\db\models\base.py", line 116, in >__new__
kwargs = {"app_label": package_components[app_label_index]}

(模型所在的应用标题为Rolls) 这如何或为什么会失败?如何设置 app_label 以使单元测试正常工作?

【问题讨论】:

    标签: django python-3.x


    【解决方案1】:

    基本错误,import语句错误。

    应该是...来自 Rolls.models

    【讨论】:

    • 没错。您应该在models 之前至少使用一个点。即使你想省略里面的应用名称,你也可以使用from __future__ import absolute_importfrom . import models。或者您应该在导入测试之前位于应用的父目录中。
    【解决方案2】:

    您需要将def __str__(self): 添加到models.py 中的Foodie 模型中。

    class Foodie(models.Model):
        #some fields
    
        def __str__(self):
            # you access to model fiels here 
            return self.label
    

    另请参阅doc 可能会对您有所帮助。

    【讨论】:

    • 哈桑,谢谢您的回复。但是,这并不能解决问题,我认为这是某种配置问题。
    猜你喜欢
    • 1970-01-01
    • 2020-11-11
    • 2011-11-03
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多