Reputation: 634
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.
Upvotes: 0
Views: 2122
Reputation: 634
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)
},
});
Upvotes: 2
Reputation: 7777
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');
}
}
});
Upvotes: 0