Asher11
Asher11

Reputation: 1325

Django - 403 (Forbidden): CSRF token missing or incorrect with Ajax call. Tried everything

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:

  1. suprisingly the csrf_exempt decorator does not work
  2. 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 the ajax calls)
  3. I can pick up the django token easily both via javascript or via django {{ token }}
  4. django.middleware.csrf.CsrfViewMiddleware is present in the settings.py
  5. python 3.8; django 2.2
  6. [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

b) Adding CSRFToken to Ajax request

c) https://docs.djangoproject.com/en/2.2/ref/csrf/

Upvotes: 2

Views: 4235

Answers (1)

harshil suthar
harshil suthar

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

Related Questions