I'm seeking to understand how the ViewSet compliments URL routing when used with routers in the context of Django REST framework. When I'm requesting a collection at api/v2/people/
, a 404 response is returned. I'm not clear on what else is required for the view to render in the browser and get a 200 status code as a part of the response?
urls.py
from django.urls import path, include
from rest_framework import routers
from people import views
router = routers.SimpleRouter()
router.register(r'people', views.PersonViewSet, basename="people")
urlpatterns = [
path('admin/', admin.site.urls),
path('api-path/', include('rest_framework.urls')),
path('api/v2/people/', include(router.urls), name="people")
]
people/views.py
from rest_framework.viewsets import ViewSet
from .models import Person
from .serializers import PersonSerializer
class PersonViewSet(ViewSet):
def list(self, request):
queryset = Person.objects.all()
serializer = PersonSerializer(queryset, many=True)
return Response(serializer.data)
As per your configuration, It should try this URL api/v2/people/people/
Or change
urlpatterns = [
path('admin/', admin.site.urls),
path('api-path/', include('rest_framework.urls')),
]
and then access api/v2/people/
You probabely have defined you app level urls.py like this,
# your app level urls.py
urlpatterns = [
.....
.....
path('people/',<Your view>, name='people-list'),
]
and in your root urls.py,
# your root level urls.py
urlpatterns = [
.......
path('api/v2/people/', include(router.urls), name="people")
]
so after appending both, the final url endpoint is, api/v2/people/people/
but your are requesting api/v2/people/
so either remove people/
from your root urls.py like this,
# your root level urls.py
urlpatterns = [
.......
path('api/v2/', include(router.urls), name="people")
]
and then request api/v2/people/
OR , request with api/v2/people/people/
OR , remove people/
from your app level urls.py,
# your app level urls.py
urlpatterns = [
.....
.....
path('',<Your view>, name='people-list'), # this is not a good option though
]
and then request api/v2/people/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.