How to fix path lines order error in Django/Python?

I have strange error with urls.py file

two lines:

    path('<slug:postcategory_slug>/<slug:slug>', post_detail, name='post_detail'),
    path('<slug:category_slug>/<slug:slug>', product_detail, name='product_detail'),

If line with post_detail stands first view.product_detail render with error 404:

No Post matches the given query.
Request Method: GET
Request URL:    http://127.0.0.1:8000/pryamye-shlifmashiny/pnevmoshlifmashina-s150z66a
Raised by:  apps.blog.views.post_detail

And view.post_detail works well

But if line with product_detail stands first, like

    path('<slug:category_slug>/<slug:slug>', product_detail, name='product_detail'),
    path('<slug:postcategory_slug>/<slug:slug>', post_detail, name='post_detail'),

view.product_detail works well But view.post_detail render with 404 error

No Post matches the given query.
Request Method: GET
Request URL:    http://127.0.0.1:8000/posts/pnevmaticheskij-udarnyj-gajkovert-at-238
Raised by:  apps.store.views.product_detail

Other config looks well, and URLS works

PLS help me figure out what the problem is

I do not know what the problem is, all the other files are fine,

Your paths overlap, so it will always fire the first view. Even if it turns out there is no slug for that PostCategory. Django just looks at the pattern of the path, and then fires the view. So the first pattern that matches, gets control. This thus means that your second path will never fire, because all paths by the second one are covered by the first one.

Make the paths non-overlapping, for example by adding a prefix:

urlpatterns = [
    path(
        'post/<slug:postcategory_slug>/<slug:slug>',
        post_detail,
        name='post_detail',
    ),
    path(
        'product/<slug:category_slug>/<slug:slug>',
        product_detail,
        name='product_detail',
    ),
]
Вернуться на верх