python - 从 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>
解决方案
我认为你有几个错误。
更改网址:
path('categories/<int:pk>/', views.item_category, name="item_category"),
您的功能令人困惑。您不希望变量与获取对象的函数同名,而 cat_id 是对象而不是整数
def item_category(request, pk): cat = get_object_or_404(Categories, pk= return render(request, 'items_modal.html', {'item_category': cat})
显示标识:
<h5 class="modal-title" id="exampleModalLabel">< ahref="{% url 'item_category' item_category.id %}">{{ item_category }}</a></h5>
推荐阅读
- powershell - 如何从 SearchString 中获取 ObjectID 列表以获取 Get-MsolContact
- python - 使用 Python 从网站查询数据(网页抓取)时,如何避免被服务器阻止?
- docker - docker-compose 中的 DNS 使用 VPN 容器:
- css-selectors - CSS 仅选择没有以 this 开头的类的元素
- r - 主要按值出现在列中的次数对数据帧进行排序,其次按第二列
- python - 让 Spacy 与 Pyspark 一起正常工作,但在 UDF 中出现 Typeerror 错误
- python - Django OneToOneField 允许在线一个参考
- ruby-on-rails - Rails 5.2 资产在生产中未正确加载
- php - codeigniter 中的“页面未正确重定向”错误
- sql - 如何在动态数据透视查询中用空字符串替换 NULL 值