How to disable csrf in modelviewset django-rest-framework?

How to disable csrf in modelviewset django-rest-framework?

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

And my application is api server. Therefore, I do not need to use csrf.

But I do not know how to disable csrf.

Please give me an example!

+7
python django django-rest-framework
source share
3 answers

CSRF applies only if you use SessionAuthentication. If you use one of the other forms of authentication (e.g. TokenAuthentication), it is not required.

+2
source share

You need to wrap the 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'), 
+2
source share

Also make sure api-auth is not included in your urls.

0
source share

All Articles