I have a parent URLconf:
from django.conf.urls import include, patterns, url
urlpatterns = patterns('',
(r'^main/(?P<name>[^/]+)/(?P<region>[^/]+)/(?P<id>[^/]+)/', include('foo')),
)
And a child URLconf (included in the parent) that includes a redirect:
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^view/$', RedirectView.as_view(url='/main/%(name)s/%(region)s/%(id)s/detail')),
)
(Essentially, I'm trying to redirect a path that looks like /main/product/1/134/view
to a path that looks like /main/product/1/134/detail
.)
The Django documentation says that "An included URLconf receives any captured parameters from parent URLconfs."
But when I try access /main/product/1/134/view
, I get a KeyError
because name
isn't recognized.
Is there some other way that I have to reference the received captured parameters in the RedirectView?
Note: I don't get an error when I do the whole thing in the parent URLconf:
urlpatterns = patterns('',
(r'^main/(?P<name>[^/]+)/(?P<region>[^/]+)/(?P<id>[^/]+)/view/$', RedirectView.as_view(url='/main/%(name)s/%(region)s/%(id)s/detail'))
)
This section of the docs suggests that you should be using two percent signs instead of one:
The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output.
So in your case, try:
url(r'^view/$', RedirectView.as_view(url='/main/%%(name)s/%%(region)s/%%(id)s/detail')),
It might be cleaner to use the pattern_name
argument instead of url
. The args
and kwargs
will be used to reverse the new url.
url(r'^view/$', RedirectView.as_view(pattern_name='name_of_url_pattern_to_redirect_to')),
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.