'Django use urls with same ending

I ahve a django project with the application web-api and the following url configuration:

main project urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('web-api/', include('webapi.urls')),
]

application web-api/urls.py

urlpatterns = [
    path('<param1:param1>/summary', Param1Summary.as_view()),
    path('<param1:param1>/item/<int:id>/summary', ItemView.as_view()),
]

The /web-api/param1/summary endpoint works but /web-api/param1/item/12121/summary does not work and returns a 404 status code.

If I change the <param1:param1>/item/<int:id>/summary' to <param1:param1>/item/<int:id>/whatever, in the web-api/url.py I get the desired results.

I have tried using url regex without succees.

Any ideas on how to solve the problem?

Thanks in advance!



Solution 1:[1]

Not an general answer but worked in my case.

Changing the order of the urls solved the issue. The urls in web-api/urls.py had to be in the following order:

urlpatterns = [
    path('<str:param1>/item/<int:pk>/summary', ItemView.as_view()),
    path('<str:param1>/summary', Param1Summary.as_view()),
]

Solution 2:[2]

I'm not sure but you can reorder the urls in this way and add name spaces so you can call them from html template or from other views as well:

urlpatterns = [
    path('summary/<param1:param1>', Param1Summary.as_view(), name='summary_parm')
    path('summary/<param1:param1>/item/<int:id>', ItemView.as_view(),  name='summary_item'),
]

Solution 3:[3]

Update your application web-api's urls.py like this.

urlpatterns = [
    path('<param1:param1>/item/<int:id>/summary', ItemView.as_view()),
    path('<param1:param1>/summary', Param1Summary.as_view()),
]

Just swap their sequence, this will work.

Solution 4:[4]

First, "param1" is not a valid url parameter type (see the docs), so you probably wanted to use '<str:param1>/summary' and '<str:param1>/item/<int:pk>/summary'.

Second, you should name the url variable "pk" as mentioned in django docs here, and not "id".

it looks for pk and slug keyword arguments as declared in the URLConf, and looks the object up either from the model attribute on the view, or the queryset attribute if that’s provided

It should look like this:

urlpatterns = [
    path('<str:param1>/summary', Param1Summary.as_view()),
    path('<str:param1>/item/<int:pk>/summary', ItemView.as_view()),
]

Alternatively, you can set the pk_url_kwarg = "id" on your view to let the get_object() method know how to query for the object. See in the docs

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 Charalamm
Solution 2 Husam Alhwadi
Solution 3 Rezaul Karim Shaon
Solution 4