Reputation: 6255
I am getting a CSRF cookie not set when making an ajax call from jquery to django views.index (I have tried everything i have seen on other stackoverflow posts, see list at bottom of post)
My ajax call:
board.delete_comment = function(){
$(this).closest("div").slideUp()
$.ajax("http://localhost:8000/"+$(this).val(),{
type: "POST",
beforeSend: function(xhr, settings) {
var csrftoken = getCookie('csrftoken')
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function (data) {
console.log(data)
}
});
};
My views.index function:
@csrf_exempt
def delete_me(comment_id):
comment = get_object_or_404(Comment, pk=comment_id)
comment.delete()
return "success"
My URL pattern:
url(r'^(?P<comment_id>[0-9]+)/$', views.delete_me, name='delete'),
Upon calling the delete_comment function in javascript a 403 forbidden error is triggered. I have tried everything i have seen on existing stack overflow boards:
-installing and adding corsheaders to settings
-including a @csrfexempt decorator in views.index
-setting CSRF_COOKIE_SECURE to false in settings
-adding the csrftoken header to the request (per django documentation)
-setting a CSRF_TOKEN on the window in my html
Nothing seems to work... Anyone have a suggestion on how to resolve this issue? Or what the issue may be.
Upvotes: 2
Views: 409
Reputation: 186
You may have a cross-domain issue since you are hard-coding http://localhost:8000/ in your ajax call. This could be why the request is being rejected. Try to replace 'http://localhost:8000/' with '/' if this is the url you are targeting.
Upvotes: 1