你需要装饰工作dispatch
方法csrf_exempt
。它所做的是将csrf_exempt
视图函数本身的属性设置为True
,然后中间件在(最外面的)视图函数中对此进行检查。如果只需要修饰几种方法,则仍然需要csrf_exempt
在该dispatch
方法上使用,但是可以csrf_protect
在例如上使用put()。如果GET,HEAD,OPTIONS
或TRACE
使用HTTP方法不管你把装修与否也不会被选中。
class ChromeLoginView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(ChromeLoginView, self).dispatch(request, *args, **kwargs)
def get(self, request):
return JsonResponse({'status': request.user.is_authenticated()})
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return JsonResponse({'status': True})
return JsonResponse({'status': False})
这是dispatch()
必须修饰的方法。
从Django 1.9开始,你可以method_decorator
直接在类上使用:
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt, name='dispatch')
class ChromeLoginView(View):
def get(self, request):
return JsonResponse({'status': request.user.is_authenticated()})
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return JsonResponse({'status': True})
return JsonResponse({'status': False})