正常请求
1.需要在views结尾传递context_instance=RequestContext(request)
2.然后在模板的form标签内添加{% csrf_token %}
异步请求
第一种
1.增加装饰器from django.views.decorators.csrf import csrf_exempt
2.在views请求函数添加该装饰器 可以在请求中屏蔽到跨站检测-----------------此处是屏蔽,牺牲了安全性
第二种
修改Ajax的请求头信息
1.下载qjeury cookie plugin
2.导入其中的jQuery.cookie.js文件
3.保存下面代码到csrftoken.js文件 并在jquery.cookie.js下方导入
[javascript] view plaincopyfunction csrfSafeMethod(method) { // these HTTP methods do not require CSRF PRotection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } function sameOrigin(url) { // test that a given url is a same-origin URL // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative. !(/^(////|http:|https:).*/.test(url)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { // Send the token to same-origin, relative URLs only. // Send the token only if the method warrants CSRF protection // Using the CSRFToken value acquired earlier var csrftoken = $.cookie('csrftoken'); xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); 4.完成后 测试 请求不会在出现403csrf提示错误原理:获取csrf值后 通过ajaxSetup修改所有ajax的默认请求的头信息
其他具体请参考原文档
新闻热点
疑难解答