Issue
I have a view that takes two optional keyword arguments: team and year_month
def monthly_data_list(request, year_month:str=None, team=None):
From the template, I want to call different combinations with either one of these 2 parameters, or both.
Django docs gives this example of implementing this:
path('monthly/list/', views.monthly_data_list, {'team':None, 'year_month'=None },name='monthly-data-list'),
However, calling this URL from the template with one or both arguments gives me a NoReverseMatch error:
hx-get="{% url 'drivers:monthly-data-list' team=None year_month=current_year_month %}"
I found a workaround suggested here, which is to define paths for all combinations of parameters. This works with 2 parameters, but gets complicated on more.
How do you correctly implement multiple optional parameters?
Solution
You misunderstand the documentation. If you write a path:
path(
'monthly/list/',
views.monthly_data_list,
{'team': None, 'year_month': None},
name='monthly-data-list',
),
that path will not take any parameters at all, optional or not. The path will accept /monthly/list/
as path, and it will fill in None
for team
and year_month
.
Passing these parameters is often done if your view can be served through multiple patterns, like:
urlpatterns = [
path(
'monthly/list/',
views.monthly_data_list,
{'team': None, 'year_month': None},
name='monthly-data-list',
),
path(
'monthly/list/<str:team>/',
views.monthly_data_list,
{'year_month': None},
name='monthly-data-list',
),
path(
'monthly/list/<str:team>/<str:year_month>/',
views.monthly_data_list,
name='monthly-data-list',
),
]
so now we have three patterns, one without any team
or year_month
, and then we use None
instead, one with /<str:team>/
, in which case we will fill in None
for `year_month, and finally one where one can specify both.
In that canse we thus can make a reverse by mentioning the parameters necessary, so int his case for example:
{% url 'monthly-data-list' team='Foo' %}
this will then pick the second path, and fill in 'Foo'
for the team
, and it will call the monthly_data_list
with None
for year_month
.
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.