0

I have a Class Based View called ChannelAuth that for testing purposes we have decorated with @csrf_exempt. This isn't final, but nonetheless I'd like an answer for the sake of learning.

@csrf_exempt
class ChannelAuth(views.APIView):
    def post(self, request, *args, **kwargs):
        if not request.data:
            return JsonResponse({'Error': 'Data is malformed.'}, status=400)
....

When using a decorator, though, we are "wrapping" the class so to speak in a function.

This means when we use ChannelAuth.as_view() we aren't actually accessing the as_view() attribute as expected, because it doesn't exist on the "wrapper function" thus throwing an AttributeError.

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/auth/channels/', ChannelAuth.as_view(), name="channel_auth")
    ]

So my question is how would I still utilize a decorator like @csrf_exempt on a Class Based View properly?

CodeSpent
  • 1,684
  • 4
  • 23
  • 46

1 Answers1

0

The initial solution is to use Django's method_decorator() on the targeted method.

from django.utils.decorators import method_decorator

class ChannelAuth(views.APIView):
    @method_decorator(csrf_exempt, name='post')
    def post(self, request, *args, **kwargs):
        if not request.data:
            return JsonResponse({'Error': 'Data is malformed.'}, status=400)
....
CodeSpent
  • 1,684
  • 4
  • 23
  • 46