[Answered ]-Django url patterns – how to make slug url work for multiple views

2👍

Django matches the first regex, in this case the product_detail view. By default, Django doesn’t have a way to try each url in turn, so the category view will never be called with your current urls.

The easiest fix is to namespace your urls. This might be a good idea – at the moment, you’ll have problems if you ever have a category and a product with the same slug.

url(r'^products/(?P<slug>[\w-]+)/$', ProductDetailView.as_view(), name='product_detail'),
url(r'^categories/(?P<slug>[\w-]+)/$', CategoryDetailView.as_view(), name='category_detail'),

Another option is to create a single view, say product_or_category. In that, you could test to see whether the slug matches a category or slug, and continue. This will work, but you might have a bit of duplicated code, and it might not seem as as elegant as the two class based views you currently have.

url(r'^(?P<slug>[\w-]+)/$', product_or_category, name='product_or_category'),

Finally, there’s a project django-multiurl that appears to do what you want. I have never used it, so I can’t make any claims for it.

Leave a comment