In Django template I used:
<form action="/user" method="post">{% csrf_token %} {{ form.as_p|safe }} <input type="submit" value="Submit" /> </form>
But error when I change to jinja2 template engine
:
Encountered unknown tag 'csrf_token'
My question: csrf_token protection
in jinja2
is required?
If required, how to do this?
Thanks in advance!
Using the django template backend you would have called {% csrf_token %} , but using the Jinja2 backend you will call it using {{ csrf_input }} (you can get just the token value instead of the token input using {{ csrf_token }} ).
csrf_token. Django has a {% csrf_token %} tag that is implemented to avoid malicious attacks. It generates a token on the server-side when rendering the page and makes sure to cross-check this token for any requests coming back in. If the incoming requests do not contain the token, they are not executed.
Jinja is a web template engine for the Python programming language. It was created by Armin Ronacher and is licensed under a BSD License. Jinja is similar to the Django template engine but provides Python-like expressions while ensuring that the templates are evaluated in a sandbox.
It seems Jinja2 works differently:
Use <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
where in Django templates you use {% csrf_token %}
source : http://exyr.org/2010/Jinja-in-Django/
I know this is an old question, but I wanted to update it with the proper way to support the csrf_token
when using the new django.template.backends.jinja2.Jinja2
available in Django 1.8+. Using the django template backend you would have called {% csrf_token %}
, but using the Jinja2 backend you will call it using {{ csrf_input }}
(you can get just the token value instead of the token input using {{ csrf_token }}
).
You can see the details in the django.template.backends.jinja2.Jinja2
source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With