Search code examples
python-3.xdjangodjango-templates

Python Django urls.py do not remove part of the address


I have urls.py as is. If I go to /catalog/product/"path" then on this page I can't specify a URL that won't include /catalog/product/"path". Please tell me how to change urls.py so that in the html template I can call values ​​different from /catalog/product/"path"

My template

<div class="PD-local">
                    <a href="/">Главная</a>
                    &emsp;&gt;&emsp;
                    <a href="{{ index.category.slug }}">{{ product.category.name }}</a>
                    &emsp;&gt;&emsp;
                    <a href="{{ category.slug }}">{{ product.name }}</a>
                </div>

My urls.py

urlpatterns = [
path('search/', views.catalog, name='search'),
path('<slug:category_slug>/', views.catalog, name='index'),
path('product/<slug:product_slug>/', views.product, name='product'),
path('product/model/<slug:model_slug>', views.model, name='model'),

]


Solution

  • You add a leading slash, so:

    <div class="PD-local">
        <a href="/">Главная</a>
        &emsp;&gt;&emsp;
        <a href="/{{ index.category.slug }}">{{ product.category.name }}</a>
        &emsp;&gt;&emsp;
        <a href="/{{ category.slug }}">{{ product.name }}</a>
    </div>

    But, this is not a good idea. You better use the {% url … %} template tag [Django-doc] to reverse URLs:

    <div class="PD-local">
        <a href="/">Главная</a>
        &emsp;&gt;&emsp;
        <a href="{% url 'index' index.category.slug %}">{{ product.category.name }}</a>
        &emsp;&gt;&emsp;
        <a href="{% url 'index' category.slug %}">{{ product.name }}</a>
    </div>