如果是基于Django CBV,则不可以直接加在视图类的视图函数中了
此时有三种方式来对Django CBV进行CSRF验证或者不进行CSRF验证方法一,在视图类中定义dispatch方法,为dispatch方法加csrf_exempt装饰器
方法1
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
class UserAuthView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(UserAuthView,self).dispatch(request,*args,**kwargs)
def get(self,request,*args,**kwargs):
pass
def post(self,request,*args,**kwargs):
pass
def put(self,request,*args,**kwargs):
pass
def delete(self,request,*args,**kwargs):
方法二:为视图类上方添加装饰器
@method_decorator(csrf_exempt,name='dispatch')
class UserAuthView(View):
def get(self,request,*args,**kwargs):
pass
def post(self,request,*args,**kwargs):
pass
def put(self,request,*args,**kwargs):
pass
def delete(self,request,*args,**kwargs):
pass
方式三:在url.py中为类添加装饰器
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^auth/', csrf_exempt(views.UserAuthView.as_view())),
]