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.

1 Answer 1

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')
]
Sign up to request clarification or add additional context in comments.

3 Comments

Weirdly I then start getting errors in other templates like '<django.views.generic.base.RedirectView object at 0x10b2c00d0>' 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.
I had missed out as_view, the answer has been fixed now.
Thanks! Works perfectly now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.