2016-05-03 21 views
0
私はAJAX呼び出しがビューファイルからのビューファイルのコードで記述された関数からデータをフェッチするために作ってるんだ

Ajaxのジャンゴ403禁断のエラー

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) 

それに対応するURLは次のとおりです。url(r'^graph/(?P<node_id>[^/]+)$', 'adminRenderConceptGraph', name='adminRenderConceptGraph'),

Ajaxコードを使用次のとおりです。

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

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

    }, 

}); 

エラー403が表示されます。

+0

jsコードを表示します。 –

答えて

2

エラーが不足しているトークンCSRFによるものでした。 1つのシンプルな行を追加すると助けになりまし

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

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

    }, 

}); 
0

あなたのjsコードがないと、私は問題の原因を推測できません。これはおそらくCSRF protectionが原因です。 XHRはcsrf-tokenなしで要求を送信します。スクリプトの先頭で助けることができると付け加え、jQueryのを使用している場合:

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'); 
     } 
    } 
}); 
関連する問題