D
D
DamskiyUgodnik2018-04-16 22:42:13
Django
DamskiyUgodnik, 2018-04-16 22:42:13

How to handle dynamic root slug?

Hello. I started learning Django and ran into such a problem, now I'm trying to make a simple product catalog and I wanted to do it beautifully, so that the urls were without the word catalog at the beginning. For example something like this:
Product categories:
/telefoni/knopochniye/
/telefoni/knopochniye/samsung
Product page:
/telefoni/knopochniye/beliy-telefon-androyd
Interested in how to process such URLs correctly, because in all the examples that I saw, there is some kind of "static" part that you can hook onto, for example:

urlpatterns = [
    path('catalog/brand/samsung', views.brand_page, name='brand_page'),
    ...
]

And if you go further, and for example, want to have text pages in the future, the URLs of which are stored in the database, then it becomes generally unclear how to do routing correctly.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2018-04-16
@sim3x

Insert directory - writing your own routing is not for beginners

R
Rostislav Grigoriev, 2018-04-16
@crazyzubr

Try to start with three views:

from django.urls import include, re_path

urlpatterns = [
    re_path(r'^(?P<catalog>\w+)/$', views.catalog_view, name='catalog'),
    re_path(r'^(?P<catalog>\w+)/(?P<brand>\w+)/$', views.brand_view, name='brand'),
    re_path(r'^(?P<catalog>\w+)/(?P<brand>\w+)/(?P<product>\w+)/$', views.product_view, name='product'),
    ...
]

Views will accept slug as parameters, like so:
def product_view(request, catalog, brand, product):
    # ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question