简体   繁体   中英

Url with <int:pk> or <slug:slug> DJANGO

Stumped with this one, I need to be able to call an article via a pk or slug, for example user can do https://www.website.com/1 or https://www.website.com/article-slug both show the same article/page.

And if neither 1 or slug exist show default article or nothing found.

path('/', views.index, name='index'), path('slug:slug/', views.index, name='index')

Not sure how to proceed.

urlpatterns = [
path('<int:pk>/', views.index),
path('<slug:slug>/',views.index)
]

note : remove the name attribute in the path because Django cannot decide where to go because the name is a unique identifier for each URL in your system or just make their names different.

another approach:

urlpatterns = [
path('<str:id_or_slug>/', views.index)
]

in views

def get(self, request, id_or_slug):
try:
   # get element by pk

try:
   #get element by slug

except:
   #return that the element is not found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM