"detail": "CSRF Failed: CSRF token missing or incorrect."

PythonEnthusiast picture PythonEnthusiast · Feb 3, 2014 · Viewed 10k times · Source

I'm making RESTful API using Tastypie, and when I try to POST/PUT/DELETE a request it says:

"detail": "CSRF Failed: CSRF token missing or incorrect.".

It works fine with GET. I've read various threads on SO, saying:

  • to delete the cookies
  • or use @csrf_exempt
  • or use @method_decorator(csrf_exempt)

but neither of it worked.

How can I over-pass this error?

views.py

class SnippetList(mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  generics.GenericAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)


    def post(self, request, *args, **kwargs):
        request._dont_enforce_csrf_checks = True
        print request.DATA
        return self.create(request, *args, **kwargs)

serializer.py

from django.forms import widgets
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES


class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

urls.py

from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

urlpatterns = patterns('',
    url(r'^snippets/$', views.SnippetList.as_view()),
    url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
)

urlpatterns = format_suffix_patterns(urlpatterns)

Answer

Void0xcc picture Void0xcc · Jul 9, 2014

Change rest_framework default permissions to AllowAny in settings.py

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
...
}