URL path converter handle empty string

Good morning,

Is there any way of handling an empty str in a url path for the following url pattern?

At the moment http://127.0.0.1:8000/discover/ results in a 404 does not exist page, which I know is expected behaviour: " str - Matches any non-empty string"

What I would like to happen is that ‘on empty string’ a redirect is called. Is that possible?

´´´

urlpatterns = [
    path('discover/<str:key>', views.Discover.as_view(), name='discover'),
]

´´´

You can create another entry on this urlpattern:

urlpatterns = [
    path('discover/', views.DiscoverRedirect.as_view(), name='discover-redirect'),
    path('discover/<str:key>', views.Discover.as_view(), name='discover'),
]

Obviously, you need to implement the DiscoverRedirect view, as this is just a example.

1 Like

Additionally, if your view identifies a default value for key, or can otherwise handle a null parameter, you could direct both URLs to the same view:

urlpatterns = [
    path('discover/', views.Discover.as_view(), name='discover-nokey'),
    path('discover/<str:key>', views.Discover.as_view(), name='discover'),
]

Thank you so much leandrodesouzadev and Ken, as usual I was overthinking it!