Django CSRF check failing with an Ajax POST request

前端 未结 22 1441
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 03:46

I could use some help complying with Django\'s CSRF protection mechanism via my AJAX post. I\'ve followed the directions here:

http://docs.djangoproject.com/en/dev/r

22条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 03:55

    The {% csrf_token %} put in html templates inside

    translates to something like:

    
    

    so why not just grep it in your JS like this:

    token = $("#change_password-form").find('input[name=csrfmiddlewaretoken]').val()
    

    and then pass it e.g doing some POST, like:

    $.post( "/panel/change_password/", {foo: bar, csrfmiddlewaretoken: token}, function(data){
        console.log(data);
    });
    

提交回复
热议问题