当我尝试将我的CreateAPIView添加到router.register时,它会引发TypeError异常:
File "/home/denys/.virtualenvs/buddha_test/lib/python3.5/site-packages/rest_framework/routers.py", line 281, in get_urls
view = viewset.as_view(mapping, **route.initkwargs)
TypeError: as_view() takes 1 positional argument but 2 were given
但是如果我直接将url添加到urlpatterns就可以了! 结果是我想看到API Root中的链接:
所以我可以写这样的东西:
urls.py
from django.conf.urls import url, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'clients-list', views.ClientList)
router.register(r'managers-list', views.ManagerList)
router.register(r'clients', views.CleintCreate, base_name='create')
urlpatterns = [
url(r'^', include(router.urls)),
]
views.py
from .models import Client, Manager
from .serializers import ClientSerializer, ManagerSerializer
from rest_framework import generics
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.generics import CreateAPIView
from rest_framework.decorators import detail_route
class ClientList(viewsets.ModelViewSet):
permission_classes = (IsAuthenticated, )
queryset = Client.objects.all()
serializer_class = ClientSerializer
class ManagerList(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticated, )
#
queryset = Manager.objects.all()
serializer_class = ManagerSerializer
class CleintCreate(CreateAPIView):
model = Client
serializer_class = ClientSerializer
permission_classes = (AllowAny,)
答案 0 :(得分:1)
您可以创建CreateAPIView
并继承GenericViewSet
,而不是实施CreateModelMixin
:
views.py
:
# ...
class ClientCreate(CreateModelMixin, GenericViewSet):
model = Client
serializer_class = ClientSerializer
permission_classes = (AllowAny,)
然后在你的urls.py
中,它就是一样的:
from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'clients-list', views.ClientList)
router.register(r'managers-list', views.ManagerList)
router.register(r'clients', views.ClientCreate, base_name='create')
urlpatterns = [
url(r'^', include(router.urls)),
]