Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to csrf_token protection in jinja2 template engine?

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!

like image 509
nguyên Avatar asked Oct 21 '11 03:10

nguyên


People also ask

What's the Jinja2 syntax for generating a CSRF token?

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 }} ).

What does {% Csrf_token %} do?

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.

Is Jinja a template engine?

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.


2 Answers

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/

like image 132
Guillaume Cisco Avatar answered Sep 21 '22 23:09

Guillaume Cisco


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

like image 22
lsowen Avatar answered Sep 21 '22 23:09

lsowen