首页 > 解决方案 > 从 Django 中的 url 获取 pk

问题描述

这是我用来在链接中获取项目 pk 的 URL 结构:

网址.py

path('categories/<int:item_category>/', views.item_category, name="item_category"),

视图.py

def item_category(request, pk):
    item_category = get_object_or_404(Categories, pk=pk)
    ids = [self.kwargs.get('pk')]
    cat_id = Categories.objects.get(pk=ids)

    return render(request, 'items_modal.html', {'item_category': item_category,
                                                'cat_id': cat_id
                                                })

现在我想使用 pk 来获取新链接上的结果,这是我的HTML

  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">{{ cat_id }}</h5>

标签: pythonhtmldjango

解决方案


我认为你有几个错误。

  1. 更改网址:

    path('categories/<int:pk>/', views.item_category, name="item_category"),

  2. 您的功能令人困惑。您不希望变量与获取对象的函数同名,而 cat_id 是对象而不是整数

    def item_category(request, pk): cat = get_object_or_404(Categories, pk= return render(request, 'items_modal.html', {'item_category': cat})

  3. 显示标识:

    <h5 class="modal-title" id="exampleModalLabel">< ahref="{% url 'item_category' item_category.id %}">{{ item_category }}</a></h5>


推荐阅读