查找了很多文档:好像是说由于浏览器的问题,有两个csrf_token(session与表单),两个csrf_token不一致导致验证不通过
– 有误请指出
- 解决参考:https://docs.djangoproject.com/zh-hans/3.2/ref/csrf/#setting-the-token-on-the-ajax-request
- 解决方法:
// 需手动创建js文件
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请求时导入此配置文件即可:
<script type="text/javascript" src="{% static 'web/js/csrf_config.js' %}"></script>