Django CBV视图解决csrf认证
urls.py
from django.conf.urls import url from appxx import views urlpatterns = [ url(r"^$", views.TestView.as_view()), ]
views.py
from django.views import View from django.shortcuts import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator
第一种方式:
class TestView(View):
@method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(TestView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): return HttpResponse("GET") def post(self, request, *args, **kwargs): return HttpResponse("POST") def put(self, request, *args, **kwargs): return HttpResponse("PUT") def delete(self, request, *args, **kwargs): return HttpResponse("DELETE")
第二种方式:
@method_decorator(csrf_exempt, name="dispatch") class TestView(View): def get(self, request, *args, **kwargs): return HttpResponse("GET") def post(self, request, *args, **kwargs): return HttpResponse("POST") def put(self, request, *args, **kwargs): return HttpResponse("PUT") def delete(self, request, *args, **kwargs): return HttpResponse("DELETE")