{% csrf_token %}

25 views
Skip to first unread message

Alex Kleider

unread,
Sep 26, 2017, 1:29:15 PM9/26/17
to Django users
I'm using test driven development (going through Harry J.W. Percival's book) and have found that the following code fails because the template tag ( {% csrf_token %} ) is rendered by the home_page view function but not by the django.template.loader.render_to_string function (and so the assertEqual test fails.)

...templates/home.html:
...
    <form method="POST">
        <input name="new_entity"
            id="id_new_entity"
            place_holder="Pick a name for your new entity." />
        {% csrf_token %}
    </form>
...

Testing code:

    def test_home_page_returns_correct_html(self):
        request = HttpRequest()
        response = home_page(request)
        returned_html = response.content.decode()
        expected_html = render_to_string('home.html')
        self.assertEqual(returned_html , expected_html)

returned_html and expected_html are the same except that returned_html contains the following line (and the other doesn't:)
        <input type='hidden' name='csrfmiddlewaretoken' value='Ev0j62rUtwdpOwjS5FN7B1VT38hE75W0JVZUJQy8IpcvzTH0MCexoRSpQvofoDoW' />
Infact, expected_html doesn't even contain the
        {% csrf_token %}
line.

Can anyone suggest a work around?
Thanks in advance.

Chris Wedgwood

unread,
Sep 27, 2017, 4:01:00 AM9/27/17
to Django users
Hi Alex

Try this:

return render_to_string('home.html', request=request)

cheers
Chris
Reply all
Reply to author
Forward
0 new messages