简体   繁体   中英

ajax django 403 forbidden error

I'm making ajax call to fetch data from the function written in view file Code from view file :

def adminRenderConceptGraph(request,group_id,node_id=None):
  if request.is_ajax() and request.method == "POST":
    group_name = u'home'
    if node_id:
    req_node = node_collection.one({'_id':ObjectId(node_id)})
    template = 'ndf/graph_concept.html'
    variable = RequestContext(request, {'node':req_node })
    return render_to_response(template,variable) 

its corresponding url is: url(r'^graph/(?P<node_id>[^/]+)$', 'adminRenderConceptGraph', name='adminRenderConceptGraph'),

the ajax code used is:

  $.ajax({
    type: "POST",
    url: "/home/ajax/graph/"+ atr,

    data:{
      group_id : '{{groupid}}',
      node_id : atr 
    },
    success: function(result) {
    alert(result) 

    },

});

I'm getting a 403 forbidden error.

The error was due to csrf token missing. Adding one simple line helped.

  $.ajax({
    type: "POST",
    url: "/home/ajax/graph/"+ atr,

    data:{
      group_id : '{{groupid}}',
      csrfmiddlewaretoken: '{{ csrf_token }}',
      node_id : atr 
    },
    success: function(result) {
    alert(result) 

    },

});

Without your js-code I can only guess what the problem is. This is most likely due to the CSRF protection . XHR sends a request without the csrf-token. If you are using jQuery, adding that at the beginning of the script can help:

function getCookie(name) {
    var cookieValue = null;
    if(document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for(var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if(cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

$.ajaxSetup({
    global: true,
    beforeSend: function(xhr, settings) {
        if(!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
            xhr.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded; charset=UTF-8');
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM