Search code examples
jquerydjangoajaxcsrf

Why I get 403 POST request error at Django?


Why I get 403 POST request error?

I do not understand what is wrong here ...

$('#id_submit').click(function(e) {
  e.preventDefault();
  var form = new FormData($('form')[0])
  form.append("image", $("input#id_image")[0].files[0])

  var data = {
    form: form,
    image_form: 123
  }

  $.ajax({
    headers: '{{ csrf_token }}',
    type: 'POST',
    data: data,
    processData: false,
    contentType: false
  })
})

Solution

  • You did not properly set the {{ csrf_token }}, you need to inject this in the POST data, or as X-CSRFToken header, but not as the entire headers. See for example the Django documentation on Setting the token on the AJAX request.

    In the POST data

    var data = {
        form: form,
        image_form: 123,
        csrfmiddlewaretoken: '{{ csrf_token }}'
    }

    In the POST header

    Or we can include this in the post headers, like:

    $.ajax({
        headers: {'X-CSRFToken': '{{ csrf_token }}' },
        type: 'POST',
        data: data,
        processData: false,
        contentType: false
    });