Wednesday, September 27, 2017

Re: {% csrf_token %}

Hi Alex

Try this:

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

cheers
Chris


On Tuesday, 26 September 2017 18:29:15 UTC+1, Alex Kleider wrote:
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.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4ff3ff89-f6ac-4e82-8d54-964be94e383c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment