【问题标题】:Pass Vars from Django template to views将变量从 Django 模板传递给视图
【发布时间】:2026-01-01 13:15:01
【问题描述】:

我正在为产品类别创建过滤器,并希望从我的模板上的相应图像中传递类别名称。 部分过滤栏:

 <a href="{% url 'product-filter' MISC%}">
    <img src="{% static 'store/images/skateboard.png' %}" alt="">
 </a>

网址:

path('search/<category>/', store_views.product_filter ,name='product-filter'),

我希望模板中的 MISC 通过并成为类别,以便我可以在视图中使用它:

# ? Filter Products by Catagory
def product_filter(request, category):
    products= Product.objects.all()
    filter=ProductFilter(category,queryset=products)
    context={'products':filter}
    return render(request,'store/filter.html',context)

目前即使在我的主页上也能看到:

NoReverseMatch at /

Reverse for 'product-filter' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P<category>[^/]+)/$']

当在 /search/MISC 上时:

NoReverseMatch at /search/MISC/

Reverse for 'product-filter' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P<category>[^/]+)/$']

【问题讨论】:

    标签: python django django-views django-templates


    【解决方案1】:

    您的 url 路由不匹配。您的错误属于类别

    path('search/<category>/', store_views.product_filter, name='product-filter'),
    

    FIX:- 将数据类型赋予 category 或任何正则表达式。喜欢:

    path('search/<str:category>/', store_views.product_filter, name='product-filter'),
    

    【讨论】:

    • 我相信 Django 无论如何默认为 str
    • 添加 str: 没有改变
    • 感谢您的编辑。向模板中的 url 添加引号似乎可以修复主页,但单击链接时仍然没有反向匹配。似乎不可能通过争论?新链接:&lt;a href="{% url 'product-filter' 'MISC' %}"&gt;
    • 你会检查&lt;a href="{% url 'product-filter' category='MISC' %}"&gt;
    • 同样的问题with arguments '('',)' URL 工作并转到 /MISC 但 url.py 似乎没有工作