详解Django的CSRF认证 (3)

方法一,在视图类中定义dispatch方法,为dispatch方法加csrf_exempt装饰器

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(StudentsView,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): pass

方法二:为视图类上方添加装饰器

@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())), ]

csrf_protect装饰器的用法跟上面一样

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpywfx.html