Menu Close

How to redirect to named url pattern directly from urls.py in Python Django?

To redirect to named url pattern directly from urls.py in Python Django, we can call the RedirectView.as_view method.

For instance, we write

from django.views.generic import RedirectView

urlpatterns = patterns('',
    url(r'^some-page/$', RedirectView.as_view(pattern_name='my_named_pattern', permanent=False)),
    #...
)

to add the some-page URL into the urlpatterns.

In it, we call RedirectView.as_view to redirect to the view with the pattern name.

And we set permanent to set whether we want the redirect to be permanent.

Posted in Python, Python Answers