Order matters
Can you spot the issue with the code below? It's an example of a common gotcha that newer Django devs encounter fairly often.
urlpatterns = [
path('<slug:slug>', ProductDetailView.as_view(), name='detail'),
path('add', ProductAddView.as_view(), name='add'),
]
Seen it yet? In this scenarios the second urlpattern will never get used. This is becaused add
is a valid slug so Django will always match the first urlpattern and then use the first view, which will likely lead to a 404 error
unless you have a Product with a slug called add
Thankfully the fix is simple and quick to implement, the lines just need to be switched around.
urlpatterns = [
path('add', ProductAddView.as_view(), name='add'),
path('<slug:slug>', ProductDetailView.as_view(), name='detail'),
]
Viola! You can now access the detail page and the add page.