Richard Richard - 4 months ago 21
Python Question

Django redirect URL with parameter, inside urls.py file?

I'm using Django 1.9. Is there any way to redirect a URL with a parameter in my urls.py file?

I want to permanently redirect a URL like

/org/123/
to the corresponding URL
/neworg/123
.

I know how to redirect within a view, but I'm wondering if there's any way to do it solely inside
urls.py
.

Answer

You can use RedirectView. As long as the old and new url patterns have the same args and kwargs, you can use pattern_name to specify the url pattern to redirect to.

from django.views.generic.base import RedirectView

urlpatterns = [
    url(r'^neworg/(?P<pk>\d+)/$', new_view, name='new_view'),
    url(r'^org/(?P<pk>\d+)/$', RedirectView.as_view(pattern_name='new_view'), name='old_view')
]