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代码即可
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):