Django CSRF检查JavaScript发布请求失败,如表单提交

时间:2016-06-17 02:17:27

标签: javascript jquery django forms

我在这里使用答案(JavaScript post request like a form submit)在浏览器的javascript中发布。但Django CSRF检查失败,因为模板中的表单中有{%csrf_token%}。怎么做?我应该添加以下代码吗?

var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", 'csrfmiddlewaretoken');
hiddenField.setAttribute("value", '{{ csrf_token }}');
form.appendChild(hiddenField);

欢迎任何提示,建议和评论。谢谢

2 个答案:

答案 0 :(得分:3)

如果您使用ajax提交表单,则还必须提交csrf令牌值。 举个例子。

$.ajax({
    type: "POST",
    url: url,
    data:{
        'csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val(),
    },
    success: function(response){
    }
});

或者你可以在ajax数据中发送序列化表格

data: $("#form").serialize(),

答案 1 :(得分:0)

我使用https://github.com/sigurdga/django-jquery-file-upload/blob/master/fileupload/static/js/csrf.js中的getCookie()函数和JavaScript post request like a form submit中的post()函数。

最终代码:

// https://github.com/sigurdga/django-jquery-file-upload/blob/master/fileupload/static/js/csrf.js
function getCookie(name) {
    console.log('getCookie');
    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;
                    }
            }
    }
    console.log('cookie:' + cookieValue);
    return cookieValue;
}
// https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit
function post(path, params, method) {
        method = method || "post"; // Set method to post by default if not specified.
        var form = document.createElement("form");
        form.setAttribute("method", method);
        form.setAttribute("action", path);
        for(var key in params) {
                if(params.hasOwnProperty(key)) {
                        var hiddenField = document.createElement("input");
                        hiddenField.setAttribute("type", "hidden");
                        hiddenField.setAttribute("name", key);
                        hiddenField.setAttribute("value", params[key]);
                        form.appendChild(hiddenField);
                }
        }
        var hiddenField1 = document.createElement("input");
        hiddenField1.setAttribute("type", "hidden");
        hiddenField1.setAttribute("name", 'csrfmiddlewaretoken');
        hiddenField1.setAttribute("value", getCookie('csrftoken'));
        form.appendChild(hiddenField1);

        document.body.appendChild(form);
        form.submit();
}

欢迎任何评论。