NVM
NVM

Reputation: 5552

How to add an optional slug in a Django Url

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

Upvotes: 1

Views: 983

Answers (2)

Mahmudul Alam
Mahmudul Alam

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

Shinra tensei
Shinra tensei

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

Related Questions