找不到PUT方法的Django Rest Framwork CSRF cookie

时间:2019-01-24 06:50:00

标签: django python-3.x django-rest-framework django-urls

我开始使用DRF,我为某些CRUD操作创建了一个基于类的视图,因此GET和POST方法可以正常工作,但是当我尝试从Postman发送PUT请求时,出现以下错误: / p>

Forbidden (CSRF cookie not set.): /post/1

我读到as_view()在内部调用csrf_exempt,所以它应该可以免除csrf令牌问题,我也尝试过使用方法装饰器,但是效果不佳。

urls.py
...
url(r'^post$',PostView.as_view()),
#url(r'^post/(?P<pk>\d+)/$',PostView.as_view()),
...

views.py ..

#-------- API for CRUD -----------------#
class PostView(APIView):
    permission_classes = (IsAuthenticated,)

    def get_object(self,pk,user_id):
        try:
            return Post.objects.get(pk=pk,user_id=user_id)
        except Post.DoesNotExist:
            raise Http404

    def get(self,request):
        post = Post.objects.get(user=request.user.id)
        serializer = PostSerializer(post)
        return Response({"success":True,"data":serializer.data},status=status.HTTP_200_OK)

    def put(self, request, pk):
        post = self.get_object(pk,request.user.id)
        serializer = PostSerializer(post, data=request.data)
        if serializer.is_valid():
            serializer.save(user=request.user.id)
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def post(self,request):
        params = request.data
        params['user'] = request.user.id
        serializer = PostSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        saved_data = self.perform_create(serializer)
        post = PostSerializer(saved_data)
        return Response({"success":True, "message":"Post  Added Successfully","data":post.data}, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()
...

有人可以让我知道我要去哪里了吗

1 个答案:

答案 0 :(得分:0)

我会尝试使用ModelViewSet来查看它是否有效。如果可行,则问题出在您的class PostView(APIView):上。如果不起作用,则可能是某些中间件,令牌,身份验证引起的。