Django Ajax CSRF 错误 403 或 500

发布于 2024-11-11 17:20:07 字数 2957 浏览 4 评论 0原文

我尝试更改管理界面。我添加了一个字段来通过 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 令牌?

I try to change the admin interface. I have added a field to change the status of the Order in my shop application via Ajax.

I base on this Django snippet Admin list_display Ajax.

This is my JavaScript code:

$(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");
                }
            },
        });

    });
});

This is my view:

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)

The view works with not Ajax call.

I read tons of articles about this and nothing works for me. I know that it is connected somehow with CSRF. In the console I get a 403 error.

I read that I have to add this JavaScript snippet anywhere:

$(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'));
    }
});

But if I add this I get 500 in the console. How can I check what kind of problem it is?
Maybe I miss a CSRF token?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

っ左 2024-11-18 17:20:07

您的 $.ajaxdata 参数未正确转义。你的问题的核心可能就在那里:

$.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");
        }
    },
});

如果你想继续使用 CSRF 中间件,你可能应该序列化一个表单:

data: $('#theForm').serialize(),

Your data parameter to $.ajax is not escaped properly. The heart of your problem probably lies there:

$.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");
        }
    },
});

If you want to continue to use the CSRF middleware, you should probably serialize a form instead:

data: $('#theForm').serialize(),
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文