如何禁用Django的CSRF验证? [英] How to disable Django's CSRF validation?
本文介绍了如何禁用Django的CSRF验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在 settings.py
中注释掉了csrf处理器和中间件行:
I have commented out csrf processor and middleware lines in settings.py
:
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickjacking protection:
139 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
140 )
但是当我使用Ajax发送请求,Django仍然响应csrf令牌不正确或缺失,并且在向标头添加X-CSRFToken后,请求将成功。
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
这里发生了什么?
推荐答案
如果您只需要一些观点不要使用CSRF,可以使用 @csrf_exempt
:
If you just need some views not to use CSRF, you can use @csrf_exempt
:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
您可以在这里找到更多示例和其他场景:
You can find more examples and other scenarios here:
- https://docs.djangoproject.com/en/1.9/ref/csrf/#edge-cases
这篇关于如何禁用Django的CSRF验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文