Django test client Response contains empty list of

2019-06-27 16:12发布

问题:

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
# []

Why is templates empty? How do I see what template was rendered?

回答1:

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

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.

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