2

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'))
)
jawns317
  • 1,726
  • 2
  • 17
  • 26

1 Answers1

4

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')),
djvg
  • 11,722
  • 5
  • 72
  • 103
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • 1
    When I use "%%" it resolves to "%" in output, but doesn't perform any string substitution, so the URL it redirects to is `'/main/%(name)s/%(region)s/%(id)s/detail` (which of course is invalid). – jawns317 Jan 23 '15 at 17:11