我在Django框架中使用ExtJs 6。我想从ext上传文件。当我提交表单时,它总是给我错误的无效csrf令牌。
禁止(403) CSRF验证失败。请求中止。
这是我的代码:
//document upload form
Ext.define('MyApp.view.UploadDocumentView', {
extend: 'Ext.form.Panel',
title : 'Upload Document',
id : 'documentUploadForm',
height: 500,
width: 400,
floating : true,
closable : true,
modal : true,
fileUpload: true,
method : 'POST',
fieldDefaults: {
labelAlign: 'top',
labelWidth: 125,
labelCls : 'formfield-input-label',
style : 'border-radius : 4px;',
inputCls : 'textfield-default',
focusCls:'textfield-default-active',
//msgTarget: 'side',
flex : 1 ,
},
items: [{
xtype: 'fieldset',
//title: 'User Info',
border : 0,
//layout: 'column',
defaultType: 'textfield',
defaults: {
//layout: 'form',
xtype: 'container',
defaultType: 'textfield',
cls : 'rounded',
style: 'width: 100%;',
},
items : [
{ xtype: 'textfield', allowBlank:false, fieldLabel: 'Doc Title', name: 'doctitle',},
{ xtype: 'filefield', allowBlank:false, fieldLabel: 'Select file', name: 'docfile'},
],
}],
buttons:[{
text: 'Upload',
handler: function(b,e){
var form = Ext.getCmp('documentUploadForm').getForm();
var token = Ext.util.Cookies.get('csrftoken');
form.submit({
url: '/document/upload/',
//headers: {'Content-Type':'multipart/form-data; charset=UTF-8', 'X-CSRFToken' : token},
headers: {'X-CSRFToken' : token},
success: function (formPanel, action) {
var data = Ext.decode(action.response.responseText);
alert("Success: " + data.msg);
},
failure: function (formPanel, action) {
var data = Ext.decode(action.response.responseText);
alert("Failure: " + data.msg);
}
});
}
}],
initComponent: function(){
this.callParent();
},
});

答案 0 :(得分:0)
将其添加为参数:
form.submit({
...
params: {
csrfmiddlewaretoken: Ext.util.Cookies.get('csrftoken')
},
要确保通过django设置cookie,请使用以下命令装饰您的视图:
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def main_view(request):
...