[Fixed]-Why do I get "CSRF cookie not set" when POST to Django REST framework?

10👍

Use the @csrf_exempt-decorator:

from django.views.decorators.csrf import csrf_exempt

@api_view(['POST'])
@csrf_exempt
def api_add(request):
    return Response({"test": 'abc'})

Update:
If you never need csrf-checks, remove the middleware. Seach for MIDDLEWARE_CLASSES in settings.py and remove 'django.middleware.csrf.CsrfViewMiddleware',.

👤tjati

5👍

Django-Rest-Framework automatically adds @csrf_exempt to all APIView (or @api_view).

Only exception is the SesssionAuthentication which forces you (correctly) to use CSRF, see the docs on CSRF or the DRF source

2👍

I solved this like this:

@api_view(['POST'])
@csrf_exempt
def add(request):
   ....

to:

@csrf_exempt
@api_view(['POST'])
def add(request):
   .....

0👍

I had the similar issue. I tried using @csrf_exempt but it did not work.

I changed ALLOWED_HOSTS = '*' to ALLOWED_HOSTS = [] and it worked for me on local.

👤sgauri

Leave a comment