问题
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!
回答1:
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/
回答2:
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
回答3:
I use Coffin. And have same problem when use:
from coffin.shortcuts import render_to_response
return render_to_response('template_name_here.html', context)
try to use instead:
from coffin.shortcuts import render
return render(request, 'template_name_here.html', context)
回答4:
in django 2.x with jinja2 templates engine you get the value of the token with {{ csrf_token }} and the complete hidden input tag with {{ csrf_input }}
source: https://django.readthedocs.io/en/2.1.x/ref/csrf.html
example:
<form action="..." method="post">
{{ csrf_input }}
...
</form>
回答5:
I had the same problem, and what I noticed is that the CSRF context processor isn't in the list of the default loaded processors. After adding 'django.core.context_processors.csrf'
to the TEMPLATE_CONTEXT_PROCESSORS
in setting.py
I could use the {% csrf_token %}
template tag normally.
来源:https://stackoverflow.com/questions/7844539/how-to-csrf-token-protection-in-jinja2-template-engine