简体   繁体   English

禁止(CSRF 令牌丢失或不正确)Django 错误

[英]Forbidden (CSRF token missing or incorrect) Django error

I am very new to Django.我对 Django 很陌生。 The name of my project is rango and I have created a URL named '/rango/tagger' that is supposed to send an object.我的项目的名称是 rango,我创建了一个名为“/rango/tagger”的 URL,它应该发送一个对象。

In my java-script, I have tried to communicate with this route by sending it an ajax request as follows:在我的 java 脚本中,我试图通过向它发送一个 ajax 请求来与这条路由进行通信,如下所示:

function send()
{
  obj = {content:$("#content").val()};
  $.post('/rango/tagger',obj,function(data){
    console.log(data);
  })
}

I have included the {% csrf_token %} in my template.我在模板中包含了 {% csrf_token %}。 However, it gives me the error as follows:但是,它给了我如下错误:

Forbidden (CSRF token missing or incorrect.): /rango/tagger
[31/Jan/2016 09:43:29] "POST /rango/tagger HTTP/1.1" 403 2274

My function tagger in views.py is as follows:我在 views.py 中的函数标记如下:

def tagger(request):
return render(request,'rango/index.html',RequestContext(request))

And I have also defined it in my URL pattern.我也在我的 URL 模式中定义了它。 I suspect my function tagger returns an incorrect value or data (made the change from HttpResponse(request) to the line above based on other SO solutions).我怀疑我的函数标记器返回了不正确的值或数据(根据其他 SO 解决方案将 HttpResponse(request) 更改为上面的行)。

However, it does not seem to work for me.但是,它似乎对我不起作用。 Where am I wrong?我哪里错了?

The AJAX request must include the csrf, because it's another HTTP request, so please copy this code: AJAX 请求必须包含 csrf,因为它是另一个 HTTP 请求,所以请复制以下代码:

// using jQuery
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;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

After you setup that before sending AJAX request to set the csrf.在发送 AJAX 请求以设置 csrf 之前进行设置之后。

source来源

Or you can do it in a short way (without the codes written above), but sending all the data in the inputs field:或者你可以用很短的方式来完成(没有上面写的代码),但是在输入字段中发送所有数据:

$.post(
    '/rango/tagger',
    $("#id_of_your_form").serialize(),
    function(data) {
        console.log(data);
    }
)

Django requires a csrf token for accepting post requests. Django 需要一个 csrf 令牌来接受发布请求。 You can also add a property csrfmiddlewaretoken = {% csrf_token %} to your data if your script is inside the template .如果您的scripttemplate您还可以将属性csrfmiddlewaretoken = {% csrf_token %}到您的data

For folks, using this inside an include js file, you can do something like:对于人们,在包含 js 文件中使用它,您可以执行以下操作:

<script>window.CSRF_TOKEN={{ csrf_token }}</script>`

and in your included js file use并在您包含的js文件中使用

$.post(url, { 'data': data + 'csrfmiddlewaretoken': window.CSRF_TOKEN },function(response){
    console.log(response)
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM