Home > front end >  Add template variable into URL and satisfy reverse match
Add template variable into URL and satisfy reverse match

Time:05-23

I found a way to inject variables into the URL per Django Template: Add Variable Into URL As Parameter, but my reverse match is not working. Do I need to use re-path and use regular expressions?

Current url.py

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

Original w/hard-coding:

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

With variable injection:

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

Error message:

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']

CodePudding user response:

This:

{% url 'registration:student_item_list_drilldown' %}

Will try to find path named student_item_list_drilldown before it is read as html. That's why it tries (and fails) to find <str:type> and <int:num> in {% url 'registration:student_item_list_drilldown' %}. You have to include that variables inside {% url ... %} brackets.

The best approach would be that:

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