我尝试更改管理界面。我添加了一个字段来通过 Ajax 在我的商店应用程序中更改订单的状态。
我基于这个 Django 片段Admin list_display Ajax。
这是我的 JavaScript 代码:
$(document).ready(function() {
$('.order-helper').css("margin", "0");
$('.order-helper').blur(function(){
var input = $(this);
$.ajax({
url: "/ajax-status-update/"+ input.attr('name') +"/",
data: order=input.attr('value'),
type: "POST",
complete: function(xhr_obj, msg){
if (msg == 'success') {
input.css("border", "1px solid green");
} else {
input.css("border", "1px solid red");
}
},
});
});
});
这是我的看法:
def order_helper(request, prod_id):
prod = get_object_or_404(FixedOrder, id=prod_id)
prod.status = request.POST.get('order')
prod.save()
return HttpResponse(content='Ok', status=200)
该视图适用于非 Ajax 调用。
我阅读了大量关于此的文章,但对我没有任何帮助。我知道它以某种方式与CSRF相关联。在控制台中,我收到 403 错误。
我读到我必须在任何地方添加这个 JavaScript 片段:
$(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'));
}
});
但是如果我添加这个,我会在控制台中得到 500。我如何检查它是什么类型的问题?也许我错过了 CSRF 令牌?