How to redirect views in Django

If you wish to redirect a URL to another in Django, there is a simple way to do it using generic views. This method is far simpler than writing a custom view, as it doesn’t require you to write anything in views.py.

In this example, we are redirecting the root URL, /, to /dashboard.

In Django 1.5, using generic class-based views, use RedirectView to redirect to any view or URL.

from django.conf.urls import patterns, url
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView

# ...

urlpatterns = patterns('',
    # Redirects to the view named app_dashboard (below)
    url(r'^$', RedirectView.as_view(url=reverse_lazy('app_dashboard')), name='index'),

    # Redirects to google.com
    url(r'^$', RedirectView.as_view(url='http://google.com'), name='index'),

    # Our destination URL
    url(r'^dashboard/$', DashboardView.as_view(), name='app_dashboard'),
    # ...
)

If you are using an older version of Django that does not support class-based generic views, use the [redirect_to][1] view instead:

from django.conf.urls import patterns
from django.views.generic.simple import redirect_to

# ...

urlpatterns = patterns('',
    # Redirects to google.com
    ('^$', 'redirect_to', {'url': 'http://google.com'}),
)

It’s that simple! No need to clutter up your views.py with various redirects. When you use reverse_lazy, you don’t even need to update your redirects when you change your URLs.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax