Search code examples
djangodjango-rest-frameworkdjango-csrf

Disable CSRF on api view method(django rest framework)


I have such api method:

@api_view(['POST'])
@login_required
def get_posts(request):
    # ...

How can I disable CSRF only on this method?


Solution

  • For function based views you can usually use the decorator csrf_exempt:

    from django.views.decorators.csrf import csrf_exempt
    from django.http import HttpResponse
    
    @csrf_exempt
    def my_view(request):
        return HttpResponse('Hello world')
    

    Update: There may be an exception for the DRF. Take a look here.