6

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)
mariodev
  • 13,928
  • 3
  • 49
  • 61
Praful Bagai
  • 16,684
  • 50
  • 136
  • 267
  • it seems, that you're using django-rest-framework but not Tastypie – SaulTigh Mar 04 '14 at 10:34
  • Does this answer your question? [CSRF Failed: CSRF token missing or incorrect](https://stackoverflow.com/questions/26639169/csrf-failed-csrf-token-missing-or-incorrect) – aaron Feb 03 '23 at 14:15

2 Answers2

0

Change rest_framework default permissions to AllowAny in settings.py

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
...
}
Void0xcc
  • 17
  • 2
  • 8
    I have `DEFAULT_PERMISSION_CLASSES` set to `rest_framework.permissions.IsAuthenticated` because I only want to allow registered users to access the API. I'm looking for another way to fix this CSRF thing. – nnyby Oct 09 '14 at 15:49
0

Try to add the CSRF token in your template, somewhere in your form :

{% csrf_token %}

See django documentation here.

Edouard Thiel
  • 5,878
  • 25
  • 33