POST method always return 403 Forbidden

前端 未结 7 1652
走了就别回头了
走了就别回头了 2021-02-19 01:46

I have read Django - CSRF verification failed and several questions (and answers) related to django and POST method. One of the best-but-not-working-for-me answer is https://sta

7条回答
  •  [愿得一人]
    2021-02-19 02:00

    The response is 403 bcoz, django requires a csrf token (included in the post data) in every POST request you make.

    There are various ways to do this such as:

    Acquiring the token from cookie and the method has been explained in article enter link description here

    or

    You can access it from DOM using {{ csrf_token }}, available in the template

    So now using the second method:

    var post_data = {
      ...
      'csrfmiddlewaretoken':"{{ csrf_token }}"
      ...
    }
    $.ajax({
      url:'url',
      type:'POST'
      data:post_data,
      success:function(data){
        console.log(data);
      },
      error:function(error){
        console.log(error);
      }
    });
    

提交回复
热议问题