我已在中注释掉了csrf处理器和中间件产品线settings.py:
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添加到标头后,请求将会成功。
这里发生了什么 ?
如果只需要一些视图而不使用CSRF,则可以使用@csrf_exempt:
from django.views.decorators.csrf import csrf_exempt @csrf_exempt def my_view(request): return HttpResponse('Hello world')