JasonTS
JasonTS

Reputation: 2589

How to add csrf_token to forms made in custom template tags in Django?

I want to write a custom template tag that returns a form. How can I make sure it includes the csrf_token?

Upvotes: 0

Views: 1288

Answers (1)

catavaran
catavaran

Reputation: 45575

Get csrf_token from context and render hidden field with it.

hidden_field = format_html(
                "<input type='hidden' name='csrfmiddlewaretoken' value='{}' />",
                context.get('csrf_token'))

See {% csrf_token %} source code for more details.

Upvotes: 3

Related Questions