我已经在django表单中启用了csrf令牌,如果我尝试上传文件,则会收到以下错误。请帮我解决。
禁止访问(未设置CSRF Cookie。):/ upload
我的html表单呈现如下。
<form id="uploadfile" action="/upload" class="dropzone needsclick dz-clickable" enctype="multipart/form-data" method="post" style="display: none;">
<input type="hidden" name="csrfmiddlewaretoken" value="I4DEvg2nDPGkaGjrynMVGh5KfGdk3Z3z">
<div class="dz-message needsclick" style="display: block;">
Drop files here or click to upload.<br>
</div>
<input type="hidden" name="cmd" value="mycmd"></form>
我的上传视图代码如下所示。
def upload(request):
# handle form upload
if request.method == 'POST':
cmd = request.POST.get('cmd','')
form = Utils.Form()
upfile = form.uploadFile(request)
....some code.....
return HttpResponse("my response")
在settings.py中的我启用了cookie和csrf,如下所示。
........
........
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
SENDFILE_BACKEND = 'sendfile.backends.development'
........
........
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
.......
答案 0 :(得分:0)
尝试使用'X-CSRFToken'标头发送请求并将csrf标记放入其中。 也许它会有所帮助 Django documentation - Cross Site Request Forgery protection - Ajax