首页 > 解决方案 > Django 如何在 url 上获取 id?

问题描述

当我点击我的菜单 url 时只获取类别名称并且 slug 无法到达 id 我该如何解决?

这是我得到的网址

    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 %}

标签: django

解决方案


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:


推荐阅读