0%

如何禁用Django的CSRF验证

❓ 我已经在settings.py中注释掉了csrf处理器和中间件行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 token is incorrect or missing”,并且在将X-CSRFToken添加到标头后,请求将会成功。

这里发生了什么 ?


✔️ 如果只需要一些视图而不使用CSRF,则可以使用@csrf_exempt:

1
2
3
4
5
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')