Home > Software design >  Why is `csrf_exempt` not needed when using django-rest-framework?
Why is `csrf_exempt` not needed when using django-rest-framework?

Time:12-09

When I make a POST request with Postman, I receive an error Forbidden (CSRF cookie not set.)

class BooksView(View):
    def post(self, request):

If I use csrf_exempt the error does not occur

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

@method_decorator(csrf_exempt, name='dispatch')
class BooksView(View):
    def post(self, request):

However, this error does not occur at all when I use django-rest-framework

from rest_framework.views import APIView

# /books
class BooksView(APIView):
    def post(self, request):

What is django-rest-framework and the APIView class doing in relation to csrf?

CodePudding user response:

All views and viewsets in django-rest-framework inherit from APIView, this class wraps itself with csrf_exempt in the as_view method.

  • Related