'drf - trailing / in url throwing error while calling post api

views.py

class FurnitureViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
    permission_classes = [AllowAny]
    serializer_class = FurnitureSerializer
    queryset = Furniture.objects.all()

@nested_view_set(FurnitureViewSet, 'furniture_id')
class TablesViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
    permission_classes = [AllowAny]
    serializer_class = TableSerializer
    queryset = Table.objects.all()

class OrdersViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    authentication_classes = []
    permission_classes = [AllowAny]
    queryset = Orders.objects.all()

urls.py

router = ExtendedSimpleRouter()
furniture_router = router.register('furnitures', FurnitureViewSet, basename='furnitures')
furniture_router.register('tables', TablesViewSet, basename="tables",parents_query_lookups=['furniture_id'])
order_router = router.register('orders', OrdersViewSet, basename="orders")

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

I have created a few apis for third party integration in my project.
Furniture and Tables apis are working fine when called from their testing portal.
Order post api is called as someurl.url/orders which throws 500 error.

You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to someurl.url/orders/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.

The apis are being accessed by another organization and being tested through their portal so I can't change the structure and I can't change the settings for the whole project for just 3 apis. How can I solve the url issue while still using ExtendedSimpleRouter since I'm using nested viewsets?



Solution 1:[1]

I solved the issue by using re_path in urls.py

router = ExtendedSimpleRouter()
furniture_router = router.register('furnitures', FurnitureViewSet, basename='furnitures')
furniture_router.register('tables', TablesViewSet, basename="tables",parents_query_lookups=['furniture_id'])

urlpatterns = [
    path('', include(router.urls)),

    re_path(r'^orders/?$', OrdersViewSet.as_view({
        'post': 'create'
    }), name="orders-list"),

    path('orders/<id>', OrdersViewSet.as_view({
        'patch': 'partial_update',
    }), name="order-detail")
]

Solution 2:[2]

Change the URL to someurl.url/orders/ and try again, Or add APPEND_SLASH=False in your setting file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 c_d_n
Solution 2 Mohammad sadegh borouny