Django CSRF check failing with an Ajax POST request

前端 未结 22 1438
佛祖请我去吃肉
佛祖请我去吃肉 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 04:04

    The issue is because django is expecting the value from the cookie to be passed back as part of the form data. The code from the previous answer is getting javascript to hunt out the cookie value and put it into the form data. Thats a lovely way of doing it from a technical point of view, but it does look a bit verbose.

    In the past, I have done it more simply by getting the javascript to put the token value into the post data.

    If you use {% csrf_token %} in your template, you will get a hidden form field emitted that carries the value. But, if you use {{ csrf_token }} you will just get the bare value of the token, so you can use this in javascript like this....

    csrf_token = "{{ csrf_token }}";
    

    Then you can include that, with the required key name in the hash you then submit as the data to the ajax call.

提交回复
热议问题