简体   繁体   中英

Using decorators on Class Based Views causes AttributeError

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?

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)
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM