禁止(CSRF令牌丢失或不正确)Django错误 [英] Forbidden (CSRF token missing or incorrect) Django error

查看:158
本文介绍了禁止(CSRF令牌丢失或不正确)Django错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Django非常陌生。我的项目名称为rango,我创建了一个名为 / rango / tagger的URL,该URL应该发送一个对象。

I am very new to Django. The name of my project is rango and I have created a URL named '/rango/tagger' that is supposed to send an object.

在我的Java脚本中,我尝试通过向其发送ajax请求来与该路由进行通信,如下所示:

In my java-script, I have tried to communicate with this route by sending it an ajax request as follows:

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

我在模板中加入了{%csrf_token%}。但是,它给了我以下错误:

I have included the {% csrf_token %} in my template. 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

views.py中的函数标记器如下:

My function tagger in views.py is as follows:

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

在我的网址格式中也定义了它。我怀疑我的函数标记器返回了不正确的值或数据(根据其他SO解决方案将HttpResponse(request)更改为上面的行)。

And I have also defined it in my URL pattern. 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).

但是,它确实似乎不适合我。我在哪里错了?

However, it does not seem to work for me. Where am I wrong?

推荐答案

AJAX请求必须包含csrf,因为它是另一个HTTP请求,因此请复制以下代码:

The AJAX request must include the csrf, because it's another HTTP request, so please copy this code:

// 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);
        }
    }
});

设置完之后,在发送AJAX请求设置csrf之前。

After you setup that before sending AJAX request to set the csrf.

来源

这篇关于禁止(CSRF令牌丢失或不正确)Django错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆