我在django rest_framework中创建了一个api,我正在用邮递员对其进行测试
GET ,DELETE
方法没有任何问题,但是在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)
这是我的Bookserializer
在serializers.py中:
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'),
]
但是当我想用 POSTMAN POST
跟随json(api2 / Books url)时:
{
"name": "biganeh",
"publisher": "ghoghnoos",
"author": 2,
"isbn": 4,
"genere": "Horror"
}
发生此错误:
AttributeError at /api2/Books
'Book_list' object has no attribute 'data'
这意味着request.data
不存在!
该如何解决?
答案 0 :(得分:0)
由于通过Book_detail类中的参数阻止了POST&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