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:
- suprisingly the
csrf_exempt
decorator does not work - tried setting up Headers/beforeSend once before all
Ajax
calls, it does not work (I tried setting the headers both in call and just once for all theajax
calls) - I can pick up the
django
token easily both viajavascript
or via django{{ token }}
django.middleware.csrf.CsrfViewMiddleware
is present in thesettings.py
python 3.8; django 2.2
- [UPDATE] I tried removing
contentType
to no avail as well
here 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