Reputation: 1325
I know this is a well worn question and I scoured the web and this website finding countless answers that boil down to the very same solutions and none of them worked for me and I do not know why. my info/trials so far:
csrf_exempt
decorator does not workAjax
calls, it does not work (I tried setting the headers both in call and just once for all the ajax
calls)django
token easily both via javascript
or via django {{ token }}
django.middleware.csrf.CsrfViewMiddleware
is present in the settings.py
python 3.8; django 2.2
contentType
to no avail as wellhere below you can see the different trials in /*...*/
var csrftoken = '{{ csrf_token }}' $.ajaxSetup({ crossDomain: false, beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrftoken) } }); $.ajax({ url: '/do_things/', type: 'POST', contentType: 'application/json', data: { /*'csrfmiddlewaretoken': csrftoken*/ }, beforeSend: function (xhr) { /*xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');*/ /*xhr.setRequestHeader('X-CSRFToken', csrftoken);*/ /*xhr.setRequestHeader('X-CSRF-Token', csrftoken);*/ }, headers: { /*'X-CSRFToken': csrftoken,*/ /*'X-CSRF-Token': csrftoken*/ }, success: function (data) { console.log('Fill all the tables') } })
on the view side
@login_required(login_url='/login/') def do_things(request): if request.method == "POST": ...
on the url
side ( in case I messed up something here):
urlpatterns = [ #... path('r/', views.do_things, name='do_things'), ]
Resources:
a) Forbidden (CSRF token missing or incorrect.) | Django and AJAX
b) Adding CSRFToken to Ajax request
c) https://docs.djangoproject.com/en/2.2/ref/csrf/
Upvotes: 2
Views: 4235
Reputation: 179
let csrftoken = '{{ csrf_token }}'
$.ajax({
type: "POST",
headers:{'X-CSRFToken':csrftoken},
url: "{% url 'Wishlist' %}",
data: {'product_id':product_id},
success: function (response) {
console.log(response, typeof(response))
}
})
I used simple ajax with csrf in the header and it's working fine.
when i use your code in mine, so function calls but data gets blank. i have refered this Django csrf token for Ajax
Upvotes: 3