Page not found erro with drf-nested-routers

242 Views Asked by At

I'm using

Django: 2.0  
Djanfo REST Frameword: 3.8.2
drf-nested-routers: 0.90.2

My contacts/views.py

class ContactViewSet(viewsets.ModelViewSet):
    serializer_class = ContactSerializer
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        return Contact.objects.filter(user=self.request.user)

class ContactPhoneNumberViewSet(viewsets.ModelViewSet):
    serializer_class = ContactPhoneNumberSerializer
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        print(self.kwargs)
        phone_numbers = ContactPhoneNumber.objects.all()
        return phone_numbers

and app/urls.py

from rest_framework_nested import routers

from contacts.views import ContactViewSet, ContactPhoneNumberViewSet

router = routers.SimpleRouter()
router.register(r'contacts', ContactViewSet, 'contacts')
contact_router = routers.NestedSimpleRouter(router, r'contacts', lookup='contact')
contact_router.register(r'phone_number', ContactPhoneNumberViewSet, base_name='contact-phone-numbers')

api_urlpatterns = [
    path('', include(router.urls)),
]

urlpatterns = [
    path('api/', include(api_urlpatterns)),
    url(r'^admin/', admin.site.urls),
]

using this setup, I'm able to access

/api/contacts/           # <= list all contacts
/api/contacts/<pk>/      # <= contact detail

But on trying to access

/api/contacts/<pk>/phone_number/           # <= list all phone numbers

It is giving Page Not Found error.

I also tried passing <phone_number_pk> but still Page not Found error is received.

1

There are 1 best solutions below

0
On BEST ANSWER
api_urlpatterns = [
    path('', include(router.urls)),
    path('', include(contact_router.urls)),
]

you also need to register nested urls separately