【问题标题】:Check for template fails because "No templates used to render the response"检查模板失败,因为“没有用于呈现响应的模板”
【发布时间】:2017-07-29 20:45:57
【问题描述】:

我正在通过 Harry J. W. Percival 使用 Python 进行测试驱动开发。我有一个带有以下代码的 Django 视图:

def view_list(request, list_id):
        list_ = List.objects.get(id=list_id)
        items = Item.objects.filter(list=list_)
        return render(request, 'list.html', {'items':items})

以及下面的 Django 测试:

def test_uses_list_template(self):
        list_ = List.objects.create()
        response = self.client.get('/lists/%d' % (list_.id,))
        self.assertTemplateUsed(response, 'list.html')

urls.py 有以下条目:

url(r'^lists/(.+)/$', views.view_list, name='view_list'),

测试失败并出现以下错误:

self.fail(msg_prefix + "No templates used to render the response")
AssertionError: No templates used to render the response

这非常令人惊讶,因为当我使用浏览器手动评估视图时,视图渲染成功。并且自动功能测试正常运行。

我查看了 HTTP 服务器,它显示了与此测试类似的情况的重定向: [时间]“GET /lists/2 HTTP/1.1”301 0 [时间] "GET /lists/2/ HTTP/1.1" 200 476

【问题讨论】:

    标签: python django python-3.x django-views tdd


    【解决方案1】:

    由于 URL 是 /lists/%d 而不是 /lists/%d/ (注意第二个 URL 上的尾部斜杠),测试失败了。因此,self.client.get 导致重定向 (301) 而不是成功(200)。使用末尾的斜线更改测试。

    response = self.client.get('/lists/%d/' % (list_.id,))
    

    还要注意obeythetestinggoat.comPercival 声明“Django 有一些内置代码可以在有人请求几乎正确的 URL 时发出永久重定向 (301),除了缺少的斜杠。”

    【讨论】:

      猜你喜欢
      • 2022-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2019-07-24
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多