nguyên
nguyên

Reputation: 5326

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!

Upvotes: 33

Views: 15200

Answers (7)

Guillaume Cisco
Guillaume Cisco

Reputation: 2945

Yes, you still want to use Cross Site Request Forgery protection, but Jinja2 works a little differently.

Instead of this default Django Template Language string:

{% csrf_token %}

You can replace it with this for Jinja2 which has the same behavior of outputting the full hidden HTML input element:

{{ csrf_input }}

You can also use {{ csrf_token }} by itself in a Jinja2 template to get just the CSRF token itself and manually create your own form field like:

<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">

original post

docs

Upvotes: 53

This peace of JS code can fix this, it will work for both Django and Jinja2, because it is pure javaScript handling for post method form tags, you can customize it by explore it friends

I'm just getting the CSRF token from cookies which already always exist and use it in form tags

let getCookie = (name) => {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}


$(()=>{
    formTags = document.querySelectorAll('[method="POST"]')
    
    let csrfToken = getCookie('csrftoken')

    

    Array.from(formTags).forEach(formTag=>{

        var inputTag = document.createElement('input')

        inputTag.setAttribute('type', 'hidden')
        inputTag.setAttribute('name', 'csrfmiddlewaretoken')
        inputTag.setAttribute('value', [csrfToken])
    
        formTag.appendChild(inputTag)

    })
})

Upvotes: 0

Emilio
Emilio

Reputation: 2752

You don't need to do anything special anymore. csrf_token is supported in django-jinja and works out of the box.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <title>test</title>
  </head>
  <body>
    <p>This should add a hidden input tag with the token. use it in your forms</p>
    {% csrf_token %}
  </body>
</html>

Upvotes: 0

Armando Hernandez
Armando Hernandez

Reputation: 31

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>

Upvotes: 3

lsowen
lsowen

Reputation: 3828

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

Upvotes: 36

Vadim Zabolotniy
Vadim Zabolotniy

Reputation: 387

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)

Upvotes: 0

Richard Otvos
Richard Otvos

Reputation: 196

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.

Upvotes: -1

Related Questions