[英]Forbidden (CSRF token missing or incorrect.) - even though it's included
I keep getting the above error even though I have included a csrf_token
already. 即使我已经包含了
csrf_token
我仍然收到上述错误。 I've used the same csrfmiddlewaretoken
for my other ajax calls and it works fine but here im getting the forbidden error. 我为其他ajax调用使用了相同的
csrfmiddlewaretoken
,它工作正常,但在这里我得到了禁止的错误。 Any idea why? 知道为什么吗?
Here's my form: 这是我的表格:
<form method="post" enctype="multipart/form-data" id="profileImageForm">{% csrf_token %}
<label for="id_banner_image" class="change_profile_img">change
<input id="id_banner_image" type="file" name="image" />
</label>
<input type="submit">
</form>
Here's my JS: 这是我的JS:
$(document).on('submit', '#profileImageForm', function(e){
e.preventDefault();
var form_data = new FormData();
var image = document.getElementById('id_banner_image').files[0].name;
form_data.append('file', image);
$.ajax({
type:'POST',
url: '/change_banner_image/',
data : {
form_data: form_data,
csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(),
},
cache: false,
contentType: false,
processData: false,
success: function(response){
console.log('Success');
},
});
});
When I get weird CSRF errors with Django & Ajax, it's usually 'cause I'm missing these pieces: 当我在Django和Ajax中遇到奇怪的CSRF错误时,通常是因为我错过了这些片段:
https://docs.djangoproject.com/en/1.11/ref/csrf/ https://docs.djangoproject.com/zh-CN/1.11/ref/csrf/
Basically, this blob of code, provided in the above docs, will handle most of the getting and passing of CSRF tokens with your ajax calls. 基本上,上述文档中提供的这段代码将通过ajax调用处理CSRF令牌的大部分获取和传递。
// using jQuery
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');
//Now use it on ajax
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);
}
}
});
Include this on your pages and see if this solves your problems. 将其包括在您的页面上,看看是否可以解决您的问题。 I'm not sure why this particular piece of code isn't working if you say others do..hard to say without seeing other parts of the project.
我不确定如果您说其他人确实在不看项目其他部分的情况下很难说,为什么这段代码无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.