[Fixed]-Django render_to_string() ignores {% csrf_token %}

47👍

To get the csrf token to work when using render_to_string, you need to supply the request object so that the context processors run.

In Django 1.8+, you can simply pass the request as an argument

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

On earlier versions, you can use a RequestContext.

from django.template import RequestContext
render_to_string('index.html', context_instance=RequestContext(request))

20👍

Unfortunately Alasdair’s answer won’t work with Django 1.10 as the csrf_token changes on each request. Please see this gist that works on 1.10. (Altered the code a bit to fix the typo from the original gist)

class HomePageTest(TestCase):

    @staticmethod
    def remove_csrf(html_code):
        csrf_regex = r'<input[^>]+csrfmiddlewaretoken[^>]+>'
        return re.sub(csrf_regex, '', html_code)

    def assertEqualExceptCSRF(self, html_code1, html_code2):
        return self.assertEqual(
            self.remove_csrf(html_code1),
            self.remove_csrf(html_code2)
        )

5👍

You can simply add an argument like this.

render_to_string('index.html', request=request)

Please refer to the document.

0👍

As of Django 2, you can do this:

html = render_to_string('my_template.html', context, request=request)
👤Chuck

Leave a comment