Django测试客户端响应是否包含模板的空列表? [英] Django test client Response contains empty list of templates?

查看:85
本文介绍了Django测试客户端响应是否包含模板的空列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Django测试文档,Django客户端响应对象包含'templates',即:用于渲染最终内容的Template实例列表,按渲染顺序排列。对于列表中的每个模板,如果模板是从文件中加载的,则使用template.name来获取模板的文件名。(名称是一个字符串,例如'admin / index.html'。)

According to the Django testing docs, the Django client Response object contains 'templates', which is: "A list of Template instances used to render the final content, in the order they were rendered. For each template in the list, use template.name to get the template's file name, if the template was loaded from a file. (The name is a string such as 'admin/index.html'.)"

但是,即使我确信已渲染了模板,我也得到了一个空的模板列表。

However, I am getting an empty list of templates, even though I am confident that a template was rendered.

from django.test.client import Client
c = Client()
response = c.post('/signup/', {'email': 'a@b.com', 'password1': 'smith', 'password2': 'smith'}, follow=True)
print response.templates
# []

为什么模板为空?

推荐答案

您是否在交互式会话中尝试过代码? Django 文档说:

Have you tried your code in a interactive session? The Django documentation says:


尽管 *您的代码* [+]可以在Python交互式
解释器中运行,但测试客户端的某些功能尤其是与模板模板相关的
功能,仅在
运行测试时可用。
这样做的原因是Django的测试运行程序执行了一些
黑魔法,以便确定给定的
视图加载了哪个模板。这种黑魔法(本质上是对内存中的Django模板
系统的修补)仅在测试运行期间发生。

Although * your code * [+] would work in the Python interactive interpreter, some of the test client's functionality, notably the template-related functionality, is only available while tests are running. The reason for this is that Django's test runner performs a bit of black magic in order to determine which template was loaded by a given view. This black magic (essentially a patching of Django's template system in memory) only happens during test running.

在测试运行中运行它,它应该可以工作。

So if you run it in a test run, it should work.

[+]我用 替换了django文档中的 *上面示例 * 使此代码段更具可读性。

[+] I have replaced the * the above example from the django documentation with your code * to make this snippet more readable.

这篇关于Django测试客户端响应是否包含模板的空列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆