0

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?

1 Answer 1

1

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'], ...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.