将模板变量添加到URL中并满足反向匹配



我找到了一种方法来注入变量到每个Django模板URL:添加变量到URL作为参数,但我的反向匹配不工作。我需要使用重路径和正则表达式吗?

当前url.py

path('student/item/drilldown/<str:type>/<int:num>/',views.StudentBehaviorListView.as_view(),name='student_item_list_drilldown'),

原始w/硬编码:

<a href="{%url 'registration:student_item_list_drilldown' type='grade' num=6%}">

变量注入:

<a href="{%url 'registration:student_item_list_drilldown'%}?type=grade&num={{i.grade}}">{{i.grade}}th Grade</a>

错误信息:

NoReverseMatch at /registration/dashboard/
Reverse for 'student_item_list_drilldown' with no arguments not found. 1 pattern(s) tried: ['registration/student/item/drilldown/(?P<type>[^/]+)/(?P<num>[0-9]+)/\Z']

This:

{% url 'registration:student_item_list_drilldown' %}

将在将其读取为html之前尝试查找名为student_item_list_drilldown的路径。这就是为什么它尝试(和失败)在{% url 'registration:student_item_list_drilldown' %}中找到<str:type><int:num>。你必须将这些变量包含在{% url ... %}括号内。

最好的方法是:

{% url 'registration:student_item_list_drilldown' 'grade' i.grade %}

最新更新