Django: The current url path didn’t match any of generated url patterns

I implemented an api, which can create a cart with UUID. When I tried to get a cart using a url like http://localhost:8001/store/carts/b4ff4b1b9fdc4c2d8ad09a8323c805dc/, the browser returned 404 page not found. I’m sure this cart_id:b4ff4b1b9fdc4c2d8ad09a8323c805dc is stored in the store_cart table in the database. I checked the generated url patterns from django and I found out the cart url patterns were not included cart_details pattern.

Anyone knows what cause this issue?

In the

class CartItemSerializer(serializers.ModelSerializer):
class Meta:
model = CartItem
fields = [‘cart’, ‘product’, ‘quantity’]

class CartSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(read_only=True)
items = CartItemSerializer(many=True, read_only=True)
total_price = serializers.SerializerMethodField()

def get_total_price(self, cart):
    return sum([item.quantity * item.product.unit_price for item in cart.items.all()])

class Meta:
    model = Cart
    fields = ['id', 'items', 'total_price']

In the

class CartViewSet(CreateModelMixin, GenericViewSet):
queryset = Cart.objects.all()
serializer_class = CartSerializer

In the

router = routers.DefaultRouter()
router.register(‘products’, views.ProductViewSet, basename=‘products’)
router.register(‘collections’, views.CollectionViewSet)
router.register(‘carts’, views.CartViewSet)

products_router = routers.NestedDefaultRouter(
router, ‘products’, lookup=‘product’)
products_router.register(‘reviews’, views.ReviewViewSet,

carts_router = routers.NestedDefaultRouter(router, ‘carts’, lookup=‘cart’)
carts_router.register(‘items’, views.CartItemViewSet, basename=‘cart-items’)


urlpatterns = router.urls + products_router.urls + carts_router.urls

I found what caused this issue.

the class CartViewSet in my file is also needed to be inherited from “RetrieveModelMixin”.

So the code would look like this:

class CartViewSet(CreateModelMixin, RetrieveModelMixin, GenericViewSet):
queryset = Cart.objects.all()
serializer_class = CartSerializer

1 Like