Search code examples
pythondjangodjango-rest-frameworkdjango-urlsdjango-generic-views

DRF url route did not match for genericview RetrieveUpdateAPIView


I have added the following routes to my Django Rest framework project, the url is matching well and returns the list view for orders and inventories however it does not match for detail view order/<int:order_no> and inventory/<int:pk>

localhost:8000/FD/orders/ work but localhost:8000/FD/order/1/ does not match and returns

Using the URLconf defined in FriendsDigital.urls, Django tried these  
URL patterns, in this order:  
 
1. admin/  
2. ^rest-auth/  
3. ^FD/ ^inventories/$ [name='inventory_list']   
4. ^FD/  ^inventory/<int:pk>/ [name='inventory_edit']  
5. ^FD/ ^orders/ [name='orders_list']  
6. ^FD/ ^order/<int:order_no>/ [name='order_update']  

The current path, FD/order/1/, didn't match any of these

the same issue is for inventory

Urls.py

urlpatterns = [
    url('^inventories/$', InventoryList.as_view(), name='inventory_list'),
    url('^inventory/<int:pk>/', InventoryRetrieveUpdate.as_view(), name='inventory_edit'),
    url('^orders/', BusinessOrderList.as_view(), name='orders_list'),
    url('^order/<int:order_no>/',BusinessOrderUpdate.as_view(), name='order_update')
]

views.py

class InventoryList(generics.ListAPIView):
    queryset= Inventory.objects.all()
    serializer_class = InventorySerializer

class InventoryRetrieveUpdate(generics.RetrieveUpdateAPIView):
    queryset = Inventory.objects.all()
    serializer_class = InventorySerializer

class BusinessOrderList(generics.ListCreateAPIView):
    queryset = BusinessOrder.objects.all()
    serializer_class = BusinessOrderSerializer

class BusinessOrderUpdate(generics.RetrieveUpdateAPIView):
    queryset = BusinessOrder.objects.all()
    serializer_class = BusinessOrderSerializer

Django version - 3.0.7 DjangoRestFramework - 3.11.0


Solution

  • DRF lookup fields defaults to 'pk', so you have to specify the lookup_fields manually:

    class BusinessOrderUpdate(generics.RetrieveUpdateAPIView):
        queryset = BusinessOrder.objects.all()
        serializer_class = BusinessOrderSerializer
        lookup_field = 'order_no'