I need to invoke Django's reverse()
method to construct a URL for a certain view function style_specific
. Its entry in urls.py
is below:
Figure 1
url(r'^(?P<jewelry_type>[A-Za-z0-9]+)/(?P<jewelry_style_user>[A-Za-z0-9]+)/(?P<jewelry_id>[0-9]+)/$',views.style_specific,name="style_specific"),
I'm also using Algolia, (a search engine) that plugs its own parameters into the constructed URLS, so I need to use reverse()
to insert placeholders that can then be manipulated by Algolia. This previously worked when I called reverse
twice --
Figure 2
specific_url = (reverse('jewelry:specific_method',args=[model_name,177013,1337]).replace('1337','{{objectID}}')).replace('177013','{{jewelry_style}}')
where model_name
is a parameter passed into the view function constructing style_specific
's URLs, and 177013
and 1337
are placeholders that get replaced eventually. However, this approach is a hackish one that will get hard to maintain later. To that end, I wanted to replace this solution with something more flexible, along the lines of this SO answer. Ideally, the placeholders/replacements would be determined by a dictionary replace_parameters
defined like
Figure 3
replace_parameters={'placeholder_1':'replacement_1','placeholder_2':replcement_2} #and so on
Unfortunately this is where my problem comes in. In Figure 2, the parameters is passed into args
a hard-coded list. (Or at least that's what the syntax appears as) The solution I attempted to overcome this obstacle was to call replace_parameters
's keys as a list
-- that is, list(replace_parameters.keys())
par this SO answer. (See below)
Figure 4
specific_url = reverse('jewelry:specific_method',args=list(replace_parameters.keys()))
This approach yielded this NoReverseMatch
specifically:
Figure 5
Reverse for 'style_specific' with arguments '('jewelry_type', 'jewelry_style_user', 'jewelry_id')' not found. 1 pattern(s) tried: ['jewelry/(?P<jewelry_type>[A-Za-z0-9]+)/(?P<jewelry_style_user>[A-Za-z0-9]+)/(?P<jewelry_id>[0-9]+)/$']
where jewelry_type
,jewelry_style_user
and jewelry_id
are the keys from replace_parameters
.
As part of my debugging, I double-checked Figure 1's regex and verified it passed using a different view function. I also verified list(replace-parameters.keys())
by testing isinstance(list(replace_parameters.keys()),list)
. I also tried placing brackets around list(replace_parameters.keys())
but that did nothing either. Django's documentation on reverse()
implies args
should have a list
passed into it, but this is not made clear. Thus my question is: does reverse()
allow a list
object to be passed into args
or must it be hard-coded?