Reputation: 5552
I want to add an optional Stackoverlow like slug to my urls in Django
path(
r"item/<int:pk>/<slug:slug>",
ItemDetailView.as_view(),
name="item_detail",
),
How do I make the slug optional so that it works in all three cases:
Upvotes: 1
Views: 983
Reputation: 153
You can achieve this using re_path
from django.urls import re_path
urlpatterns = [
re_path(r'^item/(?P<pk>[0-9]+)(?:/(?P<slug>[-\w]+))?/$', ItemDetailView.as_view(), name="item_detail"),
]
Upvotes: 2
Reputation: 1293
The easiest way to do it is using different paths:
urlpatterns = [
path('item/<int:pk>/', ItemDetailView.as_view(), name="item_detail"),
path('item/<int:pk>/<slug:slug>/', ItemDetailView.as_view(), name="item_detail"),
]
Upvotes: 0