I would like to achieve the following routing:
example.com/recipes → [List of recipe categories]
example.com/recipes/soups → [List recipes for a certain category, in this case, soups]
example.com/recipe/lentil-soup → [Recipe, note the singular ‘recipe’ in the URL]
This is not very complicated when using the project’s root urls.py, but I struggle to get it right with nested url configuration. This is what I tried:
# mysite/mysite/urls.py
urlpatterns = [
re_path(r'^recipes?/', include('recipes.urls')),
]
# mysite/recipes/urls.py
urlpatterns = [
re_path(r'^/?$', views.categories, name="categories"),
re_path(r'^(?P<url_name>[\-_a-z0-9]+)/?$', views.category, name='category'),
re_path(r'^(?P<url_name>[\-_a-z0-9]+)/?$', views.recipe, name='recipe'),
]
There are two (obvious) problems: As “^recipes?/$” is matched at the root level, the first pattern will match example.com/recipes/, but not example.com/recipes, and if I change the root level pattern to "^recipes?/?$, the more specific patterns will create incorrect matches in reverse URLs (such as example.com/recipessoups). What’s more, the second and third patterns are indistinguishable because I cannot access the difference between plural and singular in the nested urls.py.
Should I just give up and add three patterns to my root urls.py, or is there a way to achieve my goal with nested url configuration?