django2.0 csrf 问题

django不同版本对于csrf问题处理方式不太一样,我用的django2.0,在使用ajax请

求时出现了csrf问题,网上找了一大推的解决方案,有添加 @csrf_protect,有改

settings.py文件的,有改render方式等等,都没有解决我的问题,去了django官网

搜了下ajax csrf关键字,按照官网提供的解决方案,csrf问题很快得到解决,先附上官

方解决方案链接。https://docs.djangoproject.com/en/2.0/ref/csrf/

主要是在html中增加下面几段js代码即可


                        $.ajax({
url:'xxx',
type:'POST',
data:{time: mydate.getTime()},
dataType: 'json',
beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        },
success:function(r){
console.log(r)
},
})
                function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}


     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;

}


再补充说明一个问题

If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie().

这个官网的一句提示,意思是可能有的浏览器不会自动种csrftoken cookie ,所以需要配置强制种cookie,

from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def hello(request):



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值