csrf验证
全局取消csrf验证
# setting
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# **'django.middleware.csrf.CsrfViewMiddleware',** 注释掉这个中间件
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
局部取消验证
针对视图函数
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def foo(request):
return HttpResponse("foo")
针对类的视图
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
# 在类上加装饰器需要指定为dispatch加装饰器
@method_decorator(csrf_exempt,name="dispatch")
class IndexView(View):
pass
#或者直接在dispatch方法上加装饰器
class IndexView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
# 执行父类的dispatch方法
res=super(IndexView,self).dispatch(request, *args, **kwargs)
return res
局部添加验证
在全局取消验证的情况下为局部添加验证
from django.views.decorators.csrf import csrf_protect

浙公网安备 33010602011771号