第一种:
在表单里面设置 csrf_token
第二种: 通过中间件在视图处理之前设置token
注意,必须把csrf加入到method方法为post的后面,不然不会执行。
<form action="" method="post" class="form-contain">
{% csrf_token %}
from django.middleware.csrf import get_token
from django.utils.deprecation import MiddlewareMixin
class Middleware(MiddlewareMixin):
def process_request(self,request):
get_token(request)
第三种 使用装饰器得形式 装饰在对应得视图上面
from django.views.decorators.csrf import ensure_csrf_cookie
from django.utils.decorators import method_decorator
@method_decorator(ensure_csrf_cookie,name='dispatch')
第四种:
在ajax请求的时候,将字段加入到头部
headers: {
// 根据后端开启的CSRFProtect保护,cookie字段名固定为X-CSRFToken
"X-CSRFToken": getCookie("csrf_token")
},
// get cookie using jQuery
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
let cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let 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;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// Setting the token on the AJAX request
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
如果想获取更多有关python的信息,和想玩python制作的小程序,可以关注微信公众号(dreamspy)。我们一起用python改变世界,一起用python创造梦想。