1

I have the following code:

# urls.py
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from api import views

router = routers.DefaultRouter()
router.register(r'mymodel', views.MyModelViewSet, 'mymodel')

urlpatterns = [
    # ...
    path('api/', include(router.urls)),
]

And the following ViewSet:

class MyModelViewSet(viewsets.ViewSet):
    permission_classes = (OnlyStaffCanPost,)
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

When I'm trying to access http://localhost:8000/api/mymodel/ it gives me Not Found error. I printed out router.urls, the output is:

[<URLPattern '^$' [name='api-root']>, <URLPattern '^\.(?P<format>[a-z0-9]+)/?$' [name='api-root']>]

Why my viewset doesn't get registered?

4

1 回答 1

3

This ViewSet does not provide any actions by default If you want to use CRUD for this model you should use ModelViewSet instead of it like this:

from rest_framework import viewsets

class MyModelViewSet(viewsets.ModelViewSet):
    permission_classes = (OnlyStaffCanPost,)
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

viewsets.ViewSet -> viewsets.ModelViewSet

Or if you want only one action you can use mixins like this:

from rest_framework import mixins
from rest_framework import viewsets

class MyModelViewSet(mixins.ListModelMixin,
                     viewsets.GenericViewSet):

    permission_classes = (OnlyStaffCanPost,)
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer
于 2018-09-23T16:10:50.347 回答