I’m trying to realize a POST request in Jquery to the Django server. The problem is that I need to pass the CSRF token. So I copy this code in my JS file before the code of the request. But, nothing happens. The Firebug console show me the error 500 (Internal Server Error), and if I change the Post request to a get request, it do the request.
JS File
The copied code
$(document).ajaxSend(function(event, xhr, settings) {
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]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function sameOrigin(url) {
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
function safeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
My code
$(document).ready(function(){
$.post('/favorites/delete_favorite/' + data_info[0] + '/' + data_info[1], function(data){
alert(data);
});
View.py
def delete_favorite(request, content_type=None, object_id=None):
if request.method == 'POST':
message = "Hello POST"
else:
message = "Hello"
return HttpResponse(message)
});
Solution
I had a error when I sent the url, it missed a slash, so the right solution is:
$(document).ready(function(){
$.post(‘/favorites/delete_favorite/’ + data_info[0] + ‘/’ + data_info[1] + ‘/’, function(data){
alert(data);
});
I don’t remove this post, because it’s posible someone need it.
I think this is what you are looking for, your views.py file looks fine.
Alternatively you can use
@csrf_exempton the view function: