This is the urls.py file for the main site in my Django project. Ive got a category table and a country table linked to a product table and I cant get all the urls in the code below working. If i put the category_detail url in the list just after the slug:category_slug>/slug:slug/', product_detail url those urls work and country_detail links dont. If i put the country_detail urls after the slug:category-slug>/slug:slug/', product_detail url then only the country_detail url works. Any help appreciated
from django.contrib import admin
from django.urls import path
from core.views import frontpage
from store.views import product_detail, category_detail,country_detail
urlpatterns = [
path('', frontpage, name='frontpage'),
path('admin/', admin.site.urls),
path('<slug:category_slug>/<slug:slug>/', product_detail, name='product_detail'),
path('<slug:slug>/', country_detail, name='country_detail'),
path('<slug:slug>/', category_detail, name='category_detail'),```
CodePudding user response:
If i put the category_detail url in the list just after the slug:category_slug>/slug:slug/', product_detail url those urls work and country_detail links dont. If i put the country_detail urls after the slug:category-slug>/slug:slug/', product_detail url then only the country_detail url works.
This is because Django will use the first route that matches. Since the rules to match country detail and product detail are both exactly the same, whichever one is first is the one that will match.
To solve this, you need to rethink your API design and create routes that can be matched unambiguously.
Often we design a REST API around "resources" and "collections". This means we will have a route /products/
such as to interact with a collection and /products/1
to interact with a specific product resource.
For the collection route /products
, we can add the ability to pass in query parameters to filter on a category or country with something like /products?country=United States
(note the
is the URL encoded version of a space). To allow this on the API side, you will need to get the query parameters from the request object and then add a filter to your queryset. I won't get into the details here, but you can find more information about this with some googling.
For the resource route products/1
, we might want to get related objects, like the categories for that country. In such a case, we would create a route like products/1/categories
. I will leave the details for implementing the view for this as an exercise for the reader.
CodePudding user response:
Try this
urlpatterns = [
path('', frontpage, name='frontpage'),
path('admin/', admin.site.urls),
path('product-detail/<slug:category_slug>/<slug:slug>/', product_detail, name='product_detail'),
path('country-detail/<slug:slug>/', country_detail, name='country_detail'),
path('category-detail/<slug:slug>/', category_detail, name='category_detail'),
]