3

How do I redirect all URLs starting from a particular pattern to another?

Description:

I want to be able to redirect as follows:

/pattern1/step1/ to /pattern2/step1/
/pattern1/step2/ to /pattern2/step2/
/pattern1/continue/ to /pattern2/continue/

What is the easiest way of doing this in Django URL patterns?

Alagappan Ramu
  • 2,270
  • 7
  • 27
  • 37

3 Answers3

5

RedirectView works. Capture the remainder of the path with a named kwarg. It will be passed into RedirectView.get_redirect_url, so you can interpolate it into the url you provide.

url(r'^pattern1/(?P<url>.+)$', RedirectView.as_view(url="/pattern2/%(url)s")),
#                    ^                                                ^
#                    | this url                         appears here  |
dokkaebi
  • 9,004
  • 3
  • 42
  • 60
0

You can use redirect_to generic view and add redirection urls in urls.py as:

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',
    ('^pattern1/step1/$', redirect_to, {'url': '/pattern2/step1/'}),
    #any more patters.
)

Here is documentation: Generic view redirect_to . These can take the parameters as well.

Rohan
  • 52,392
  • 12
  • 90
  • 87
0

Redirections could also be handled at the web server level.

bformet
  • 13,465
  • 1
  • 22
  • 25
  • Yes. I thought of this. But since this would be a frequent change, I wanted to check if there was a way to do this using Django itself. :) – Alagappan Ramu Oct 14 '12 at 16:49