Django CSRF check failing with an Ajax POST request

前端 未结 22 1413
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:06

    As it is not stated anywhere in the current answers, the fastest solution if you are not embedding js into your template is:

    Put before your reference to script.js file in your template, then add csrfmiddlewaretoken into your data dictionary in your js file:

    $.ajax({
                type: 'POST',
                url: somepathname + "do_it/",
                data: {csrfmiddlewaretoken: window.CSRF_TOKEN},
                success: function() {
                    console.log("Success!");
                }
            })
    

提交回复
热议问题