jQuery: setting up CSRF token for Django not working

后端 未结 2 1379
梦如初夏
梦如初夏 2020-12-12 01:44

my jQuery function looks like

$(function() {
    // activate \"New\" buttons if input is not empty
    $(\'form input[type=\"text\"]\').live(\'k         


        
相关标签:
2条回答
  • 2020-12-12 02:10

    In my case I have a template in which I don't want to have a <form></form> element. But I still want to make AJAX POST requests using jQuery.

    I got 403 errors, due to CSRF cookie being null, even if I followed the django docs (https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/). The solution is in the same page, mentioning the ensure_csrf_cookie decorator.

    My CSRF cookie did get set when I added this at the top of my views.py:

    from django.views.decorators.csrf import ensure_csrf_cookie
    @ensure_csrf_cookie
    

    Also, please note that in this case you do not need the DOM element in your markup / template: {% csrf_token %}

    0 讨论(0)
  • 2020-12-12 02:23

    <input type="hidden" name="csrfmiddlewaretoken" value="SOME_TOKEN">

    Above is the markup outputted by django. You want to grab the value of SOME_TOKEN. You will not be able to get it using the django template engine mixed with javascript since it will already be rendered into the input hidden.

    I would wrap my {{ csrf_token }} in a span/div and then use jquery to locate that span/div and grab the value of the input inside the span/div.

    0 讨论(0)
提交回复
热议问题