[Django]-How to dispatch a specific method with csrf_exempt in django class based view

2👍

You can’t dacorate only the post()/put() because as_view function in base.py doesn’t carry __dict__ methods from other methods than dispatch(). Source.
You can only decorate a class or override the dispatch() method as documentation says.

0👍

You can try this –


from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

class UserView(View):

   # Check csrf here  
   def get(self, request, pk):
      #code here

   # exempt csrf will affect only this method 
   @method_decorator(csrf_exempt)
   def post(self, request):
       #code here

You can also write it this way –

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator


@method_decorator(csrf_exempt, name='post')
class UserView(View):

   # Check csrf here  
   def get(self, request, pk):
      #code here

   # exempt csrf will affect only post method
   def post(self, request):
       #code here

Read the documentation here.

👤FORHAD

Leave a comment