How to unset csrf in modelviewset of django

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!


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.


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'),

还要确保你的urlpatterns中没有包含api-auth。

链接地址: http://www.djcxy.com/p/75368.html

上一篇: 如何编辑/更改RemoteView中的布局视图或从View创建RemoteView?

下一篇: 如何在django的modelviewset中取消设置csrf