I am completing my first course RESTful Routes on TDD.
Now I am on Part 1 Restful Routes and we are asked to refactor the views into a single ViewSet.
I have been following the tutorial provided Django REST Framework Views - ViewSets and i've combined my APIView's to a ViewSet in my views.py file:
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
class MovieViewSet(ViewSet):
movies = Movie.objects.all()
def list(self, request):
serializer = ItemSerializer(self.queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
item = get_object_or_404(self.queryset, pk=pk)
serializer = ItemSerializer(item)
return Response(serializer.data)
I am struggling with handling the URLs.
# urls.py
from django.urls import path, include
from rest_framework import routers
from .views import MovieViewSet
router = routers.DefaultRouter()
router.register("api/movies/", MovieViewSet)
urlpatterns = [
path("api/movies/", MovieViewSet),
path('', include(router.urls)),
]
Here, we created a router (using DefaultRouter, so we get the default API view) and registered the ItemsViewSet to it. When creating a router, you must provide two arguments:
The URL prefix for the views The ViewSet itself Then, we included the router inside urlpatterns.
As per these instructions I thought I needed to recreate the url that we had in the APIView i.e http://localhost:8009/api/movies/ but I get the following error.
http: error: ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')) whit', port=8000): Max retries exceeded with url: /api/movies/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnect
Can anyone help?