Django DRF Viewset URL Reversing Issue - NoReverseMatch for 'orderitem-list

I'm encountering a perplexing issue while working with Django and the Django Rest Framework (DRF). Specifically, I have two viewsets, namely OrderViewSet and OrderItemViewSet, both registered with a DefaultRouter. The problem arises when attempting to perform URL reversing for the 'orderitem-list' endpoint, where I consistently encounter a NoReverseMatch error. Surprisingly, this issue is not present when reversing the URL for 'order-list'.

router = DefaultRouter()
router.register(r"", OrderViewSet, basename="order")
router.register(r"^(?P<order_id>\d+)/order-items", OrderItemViewSet, basename="orderitem")

urlpatterns = [
    path("", include(router.urls)),
]

def test_create_order_for_anonymous_user(self, client, address):
        url = reverse("order-list")
        response = client.post(url, {})

        assert response.status_code == 403
        assert Order.objects.count() == 0

This test code works successfully

def test_create_order_item_for_anonymous_user(self, client, order):
        url = reverse("orderitem-list", kwargs={"order_id": order.id})
        response = client.post(url, {})

        assert response.status_code == 403
        assert OrderItem.objects.count() == 0

The error message is: django.urls.exceptions.NoReverseMatch: Reverse for 'orderitem-list' with keyword arguments '{'order_id': 1}' not found.

Any ideas on why this might be happening? The reverse for 'order-list' works without any issues.

Back to Top