Python + Django page redirect Python + Django page redirect python python

Python + Django page redirect


It's simple:

from django.http import HttpResponseRedirectdef myview(request):    ...    return HttpResponseRedirect("/path/")

More info in the official Django docs

Update: Django 1.0

There is apparently a better way of doing this in Django now using generic views.

Example -

from django.views.generic.simple import redirect_tourlpatterns = patterns('',       (r'^one/$', redirect_to, {'url': '/another/'}),    #etc...)

There is more in the generic views documentation.Credit - Carles Barrobés.

Update #2: Django 1.3+

In Django 1.5 redirect_to no longer exists and has been replaced by RedirectView. Credit to Yonatan

from django.views.generic import RedirectViewurlpatterns = patterns('',    (r'^one/$', RedirectView.as_view(url='/another/')),)


Depending on what you want (i.e. if you do not want to do any additional pre-processing), it is simpler to just use Django's redirect_to generic view:

from django.views.generic.simple import redirect_tourlpatterns = patterns('',    (r'^one/$', redirect_to, {'url': '/another/'}),    #etc...)

See documentation for more advanced examples.


For Django 1.3+ use:

from django.views.generic import RedirectViewurlpatterns = patterns('',    (r'^one/$', RedirectView.as_view(url='/another/')),)


There's actually a simpler way than having a view for each redirect - you can do it directly in urls.py:

from django.http import HttpResponsePermanentRedirecturlpatterns = patterns(    '',    # ...normal patterns here...    (r'^bad-old-link\.php',     lambda request: HttpResponsePermanentRedirect('/nice-link')),)

A target can be a callable as well as a string, which is what I'm using here.