我正在使用Tastypie制作RESTful API,当我尝试向POST/PUT/DELETE
发出请求时,它说:
“detail”:“CSRF失败:CSRF令牌丢失或不正确。”
它适用于GET
。我已经阅读了SO上的各种主题,说:
@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)
在settings.py中将rest_framework默认权限更改为AllowAny
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
...
}
要在使用Django REST API时禁用CSRF验证,请尝试将这些添加到settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
)
}