“detail”:“CSRF失败:CSRF令牌丢失或不正确。”

问题描述 投票:6回答:2

我正在使用Tastypie制作RESTful API,当我尝试向POST/PUT/DELETE发出请求时,它说:

“detail”:“CSRF失败:CSRF令牌丢失或不正确。”

它适用于GET。我已经阅读了SO上的各种主题,说:

  • 删除cookie
  • 或使用@csrf_exempt
  • 或使用@method_decorator(csrf_exempt)

但它都不起作用。

我怎样才能超越这个错误?

views.朋友

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)

serialize人.朋友

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.朋友

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)
django tastypie django-csrf
2个回答
0
投票

在settings.py中将rest_framework默认权限更改为AllowAny

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

0
投票

要在使用Django REST API时禁用CSRF验证,请尝试将这些添加到settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
    )
}
© www.soinside.com 2019 - 2024. All rights reserved.