Search code examples
djangodjango-formscsrfdjango-csrf

How to add csrf_token to manually created HTML form?


When creating a HTML form using Django format_html, I need to insert the csrf_token at the place of {% csrf_token %} below, since the use of {% csrf_token %} of course don't substitute when using format_html:

res = format_html('''
<form method="POST">
  {% csrf_token %}
  {}
</form>''', ...

How do I manually generate the equivalent of {% csrf_token %} which is inserted when rendering a HTML template by Django?


Solution

  • Found solution based on other SO post, and the method is to add a hidden field with csrf_token like:

    res = format_html('''
    <form method="POST">
      <input type="hidden" name="csrfmiddlewaretoken" value="{}" />
      {}
    </form>''', csrf(html_request)['csrf_token'], ...)