1

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:

  1. item/1
  2. item/1/
  3. item/1/slug
NVM
  • 5,442
  • 4
  • 41
  • 61
  • 1
    As far as I know there is no option to treat parameters in url as optional. In this case you need to create two paths linked with one view – ImustAdmit Oct 21 '20 at 14:43
  • 1
    Does this answer your question? [Django optional url parameters](https://stackoverflow.com/questions/14351048/django-optional-url-parameters) – iklinac Oct 21 '20 at 14:55

2 Answers2

2

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"),
]
Dharman
  • 30,962
  • 25
  • 85
  • 135
Mahmudul Alam
  • 143
  • 1
  • 8
0

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"),
]
Shinra tensei
  • 1,283
  • 9
  • 21