0

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.

Community
  • 1
  • 1
Richard
  • 52,447
  • 93
  • 287
  • 475

1 Answers1

2

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')
]
Dima Kudosh
  • 5,828
  • 4
  • 32
  • 43
Alasdair
  • 253,590
  • 43
  • 477
  • 449
  • Weirdly I then start getting errors in other templates like `'' is not a callable or a dot-notation path` - it's definitely the redirect that is causing the problem, as if I comment it out then the error disappears too. – Richard Aug 02 '16 at 16:17
  • I had missed out `as_view`, the answer has been fixed now. – Alasdair Aug 02 '16 at 16:20
  • Thanks! Works perfectly now. – Richard Aug 02 '16 at 16:22