在不使用表单的 Django 模板中,我想将文件上传到我的 Web 服务器。因此,我正在使用名为 dropzonejs 的 javascript 库。
我完全遵循本教程 bootstrap dropzonejs .我设置了一切以运行演示。
你看,我决定不使用 form
,所以很明显,当上传发生时,问题 csrf_token
丢失了。
我的疑问是如何在javascript
中包含csrf_token
。?
这是他们在主页上添加的关于如何添加csrf token的信息
sending - Called just before each file is sent. Gets the xhr object and the formData objects as second and third parameters, so you can modify them (for example to add a CSRF token) or add additional data.
你明白我的问题了吗?给我一些想法吗?
最佳答案
您可以查看 CSRF exempt :
from django.views.decorators.csrf import csrf_exempt
class YourView(models.View):
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super(YourView, self).dispatch(*args, **kwargs)
JavaScript配置可能看起来与此类似:
(function($){
$(function(){
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) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false,
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
})(jQuery);
关于javascript - 如何在 Django 中应用 csrf_token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25056028/