Django的REST框架HTTP POST方法问题

问题描述 投票:0回答:1

我创建在Django rest_framework的API和我与邮差GET ,DELETE方法测试它have't任何问题,但在PUT ,POST方法它提供了一些错误。

这里是我的views.py观点Book_list:

class Book_list(mixins.ListModelMixin,
                mixins.CreateModelMixin,
                generics.GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = Bookserializer

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

    def post(self,*args,**kwargs):
        return self.create(self,*args,**kwargs)

这里是我的views.py观点Book_detail:

class Book_detail(mixins.RetrieveModelMixin,
                  mixins.UpdateModelMixin,
                  mixins.DestroyModelMixin,
                  generics.GenericAPIView):

    queryset = Book.objects.all()
    serializer_class = Bookserializer

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

    def put(self,*args,**kwargs):
        return self.update(self,*args,**kwargs)

    def delete(self,*args,**kwargs):
        return self.destroy(self,*args,**kwargs)

这里是我在serializers.py` Bookserializer

class Bookserializer(serializers.ModelSerializer):
    class Meta():
        model = Book
        fields = ('id','name','publisher',
                  'author','isbn','genere')

这里是我的应用程序的urls.py

from django.urls import path , re_path ,register_converter,include
from rest_framework import routers
from . import views

urlpatterns = [

    path('Books' , views.Book_list.as_view() ,
    name = 'Book_L_2'),
    path('Book/<int:pk>' , views.Book_detail.as_view() ,
    name = 'Book_D_2'),
    path('Authors' , views.Author_list.as_view() ,
    name = 'Author_L_2'),
    path('Author/<int:pk>' , views.Author_detail.as_view() ,
    name = 'Author_D_2'),

]

但是当我想POST在与邮差JSON(API2 /图书网址):

{
        "name": "biganeh",
        "publisher": "ghoghnoos",
        "author": 2,
        "isbn": 4,
        "genere": "Horror"
    }

这个错误发生:

 AttributeError at /api2/Books
'Book_list' object has no attribute 'data'

这意味着request.data不存在!?如何解决这一问题?

django http django-rest-framework http-post postman
1个回答
0
投票

因为你封锁了POST&经由Book_detail类参数PUT方法,则仅指定PUT,DELETE,GET方法。这也是以阻断HTTP请求方法的一种方式。代码更改为按照以下,

class Book_detail(mixins.RetrieveModelMixin,
              mixins.UpdateModelMixin,
              mixins.DestroyModelMixin,
              mixins.CreateModelMixin,
              mixins.UpdateModelMixin,
              generics.GenericAPIView):

queryset = Book.objects.all()
serializer_class = Bookserializer

如有任何问题请参考此链接Mixins views

我的建议是,而不是指定这样你可以使用ModelViewset

© www.soinside.com 2019 - 2024. All rights reserved.