【发布时间】:2019-12-01 10:48:45
【问题描述】:
我为我的 django 项目创建了一个自定义模板标签,它返回一个图片 url 作为 favicon
# myapp/templatetags/customtags.py
@register.simple_tag
def get_shop_favicon():
'''
get shop favicon
'''
return Shop.objects.first().favicon.url
并像这样在 base.html 中使用它
<!doctype html>
{% load storefront_tags %}
<head>
<link rel="icon" href="{% get_shop_favicon %}" type="image/png" sizes="16x16">
</head>
<body>
...
</body>
这部分效果很好,但是在创建测试函数来测试我的视图后得到了一个 AttributeError 如下
AttributeError: 'NoneType' object has no attribute 'favicon'
这是我的测试课
# test.py
from django.test import TestCase
from django.urls import reverse
class ProductViewTest(TestCase):
'''
testing product views and urls
'''
def test_get_product_list_status_code(self):
'''
test to get all products
'''
url = reverse('prodcuts') # url name
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
注意:没有模板标签效果很好
【问题讨论】:
-
您的模板中没有
Shop对象,因此.first()将返回None。
标签: django django-templates django-tests