django - 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 %}
解决方案
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:
- How to add url parameters to Django template url tag? to give you another example.
推荐阅读
- css - 如何让表格宽度在我的一个媒体查询中移动
- python - 如何将我的程序生成的数据传输到新的海龟程序中使用?
- xamarin.forms - 我的 xamarin 表单中有两个圆圈,使用 skiasharp 绘图。如何在这两个圈子上放置不同的触摸事件处理程序?
- android - 有没有办法使用谷歌地图 api 突出显示城市内的一个区域?
- javascript - 使用 JavaScript 等到服务器中存在图像?
- java - BMI计算器,几种方法,代码检查
- flutter - 后端响应成功时打开新屏幕
- c++ - 为什么这个构造函数在传递给 std::thread 时被调用了 3 次?
- javascript - 引号中的 JavaScript onclick 处理程序给出不同的行为?
- javascript - 基于 URL 的 Jquery Tabs 添加/切换类