How does Django get id on url?

When i clicked my menu url only gets category name and slug cant reach id how can i solve that ?

This is the url i get

    def category_products (request,id,slug):
            category=Category.objects.all()
            products=Product.objects.filter(category_id=id)
            context={'products':products,'category':category,'slug':slug, }
            return render(request, 'kiliclar.html', context)
        
        urlpatterns = [
          path('category/<int:id>/<slug:slug>/', views.category_products,name='category_products'),
        ]
template
      {% recursetree category %}
        <li class="dropdown">
                            <a href="/category/{{ node.slug }}" class="nav-link dropdown-toggle arrow" data-toggle="dropdown">{{ node.title }}</a>
            {% if not node.is_leaf_node %}
 <ul class="dropdown-menu">
                    <li><a href="#">{{ children }}</a></li>
                </ul>
            {% endif %}

Upvotes: 0

Views: 1063

Answers (2)

Stephen C
Stephen C

Reputation: 718826

How does Django get id on url?

You need to supply it when you generate the "href" in the template.

The URL pattern says:

path('category/<int:id>/<slug:slug>/',
     views.category_products,
     name='category_products')

So the URL in the href in the template needs to look the same as the pattern:

href="/category/{{ node.id }}/{{ node.slug }}"

Or better still use the 'url' template function to expand the url from the pattern:

href="{% url category_products id=node.id slug=node.slug %}"

Here is a similar Q&A:

Upvotes: 1

binpy
binpy

Reputation: 4194

You need to add one more argument, it's id.

<a href="/category/{{ node.slug }}" class="nav-link dropdown-toggle arrow" data-toggle="dropdown">{{ node.title }}</a>

It should be;

<a href="{% url 'category_products' id=node.id slug=node.slug %}" class="nav-link dropdown-toggle arrow" data-toggle="dropdown">{{ node.title }}</a>

Upvotes: 0

Related Questions