csrf_exempt for class based views

Question:

Code:

class ErrorReportView(View):

    def get(self, request, *args, **kwargs):
        return HttpResponse('Hello, World!')

    @method_decorator(csrf_exempt)
    def post(self, request, *args, **kwargs):
        return HttpResponse('Hello, World!')

enter image description here

I use Postman, but I get

<p>CSRF verification failed. Request aborted.</p>

Documentation: https://docs.djangoproject.com/en/4.1/topics/class-based-views/intro/#decorating-the-class

What can I try to resolve this?

Asked By: Trts

||

Answers:

The csrf_exempt decorator should be applied to "dispatch" method. You can add the following decorator directly on top of your class, like so:

@method_decorator(csrf_exempt, name='dispatch')
class ErrorReportView(View):

    def get(self, request, *args, **kwargs):
        return HttpResponse('Hello, World!')

    def post(self, request, *args, **kwargs):
        return HttpResponse('Hello, World!')
Answered By: Maxim Kukhtenkov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.