Django-rest-framework: "CSRF Failed: CSRF cookie not set." error

Created on 17 May 2013  路  8Comments  路  Source: encode/django-rest-framework

I am using the django rest framework to perform API calls via IOS
and I get the following error
"CSRF Failed: CSRF cookie not set."

Here's my django API code:

class LoginView(APIView):
    """
    List all snippets, or create a new snippet.
    """
    @csrf_exempt
    def get(self, request, format=None):
        startups = Startup.objects.all()
        serializer = StartupSerializer(startups, many=True)
        return Response(serializer.data)

    @csrf_exempt
    def post(self, request, format=None):
        profile = request.POST

....

What can I do?

Most helpful comment

I had the same error but then i just add the _class_name.as_view()_ in _urls.py_ and it works fine ! Perhaps that would be the issue.

All 8 comments

You need to decorate the dispatch method on the class with a method_decorator or decorate the URLconf. e.g.

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(LoginView, self).dispatch(*args, **kwargs)

Hello,

Thanks for your help.

I did what you suggested, but it does not work. :( Same error.

@weina67: I had a similar error with a coworker and we tried to disabled the csrf middleware in settings.py. My machine worked but his didn't. We ended up having different versions installed of django (and maybe rest framework). He changed to django version 1.4.5 and djangorestframework 2.2.0 and was able to overcome the error. I didn't investigate the root cause.

isn't this the same as #799

This is a client issue, not a framework issue. You're client isn't including the cookie. The short answer is you probably shouldn't be using SessionAuthentication for native clients. Use a proper token auth style scheme instead, or at a minimum use Basic auth over https.

I had the same error but then i just add the _class_name.as_view()_ in _urls.py_ and it works fine ! Perhaps that would be the issue.

You need to decorate the dispatch method on the class with a method_decorator or decorate the URLconf. e.g.

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(LoginView, self).dispatch(*args, **kwargs)

this disables the csrf protection.

Except that doesn't apply for DRF as the views are already csrf exempted but the CSRF protection is enforced by the session auth, no matter how you decorate the view.

Was this page helpful?
0 / 5 - 0 ratings