Django returns 403 error when sending a POST request

后端 未结 7 2226
名媛妹妹
名媛妹妹 2021-01-31 08:27

when I\'m using following Python code to send a POST request to my Django website I\'m getting 403: Forbidden error.

url = \'http://www.sub.domain.com/\'
values          


        
7条回答
  •  别跟我提以往
    2021-01-31 08:29

    The response is 403 because 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);
      }
    });
    

提交回复
热议问题