10

How to unset csrf in modelviewset of django-rest-framework?

I'll use viewsets.ModelViewSet(http://django-rest-framework.org/api-guide/viewsets.html#modelviewset) of django-rest-framework.

And my app is api server. So I don't need to use csrf.

But I don't know how to unset csrf.

Please give me a example!

chobo
  • 4,830
  • 5
  • 23
  • 36

3 Answers3

4

CSRF is only enforced if you're using SessionAuthentication. If you're using one of the other form of authentication (eg TokenAuthentication) then it won't be required.

Tom Christie
  • 33,394
  • 7
  • 101
  • 86
  • I'm using this in my viewset: 'authentication_classes = (SessionAuthentication, TokenAuthentication)' but i'm still getting csrf error when using the Token header – Yuri Heupa May 14 '15 at 13:39
2

You need to wrap dispatch method of ModelViewSet with csrf_exempt:

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

class MyModelViewSet(viewsets.ModelViewSet):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(MyModelViewSet, self).dispatch(*args, **kwargs)

or you can achieve the same effect by wrapping the view in urls.py:

url(r'^snippets/$', csrf_exempt(snippet_list), name='snippet-list'),
url(r'^snippets/(?P<pk>[0-9]+)/$', csrf_exempt(snippet_detail), name='snippet-detail'),
mariodev
  • 13,928
  • 3
  • 49
  • 61
  • 9
    Have you actually tried this in conjunction with SessionAuthentication? I have, and I'm almost certain the DRF authentication middleware entirely ignores any such decorator. – paulmelnikow Mar 04 '14 at 21:29
  • So anyway to do that? This answer really cannot work. I have serval viewset need to be protected by csrf, while only one should not be protected by csrf. – atline Aug 01 '18 at 09:27
0

Also make sure no api-auth is included in your urlpatterns.

Yuming Cao
  • 935
  • 1
  • 10
  • 22