You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中向show_category函数直接传递参数?

Django视图函数传参:传递"g"到show_category的实现方案

一、URL路径配置(当前配置已正确)

你写的URL规则已经满足需求,通过<str:categorys>可以捕获URL路径中的字符串参数,参数名和视图函数的参数保持一致即可:

path("category/<str:categorys>", views.show_category, name="category"),

这条规则会把category/后的字符串作为categorys参数传递给视图函数。

二、HTML中a标签的href写法

要把"g"作为固定参数传入,只需在{% url %}模板标签里追加这个参数值:

<li><a class="dropdown-item" href="{% url 'category' 'g' %}">Game</a></li>

模板渲染后会生成类似/category/g的路径,自动把"g"传递给视图的categorys参数。

三、视图与模型的匹配验证

你的视图逻辑已经正确,不过注意代码里的requst是拼写错误,要改成request:

def show_category(request, categorys):
    posts = Listing_page.objects.filter(categori=categorys, open=True)
    return render(request, 'auctions/category.html', {
        "posts": posts
    })

模型里的categori字段使用了item_category选项,'g'对应Game分类,和视图的过滤逻辑完全匹配,无需额外修改。

内容的提问来源于stack exchange,提问作者atefe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:25:26