Kyle Hayes Kyle Hayes - 4 months ago 22
Python Question

Python + Django page redirect

How do I accomplish a simple redirect (e.g.

cflocation
in ColdFusion, or
header(location:http://)
in Django)?

Answer

It's simple:

from django.http import HttpResponseRedirect

def 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_to

urlpatterns = 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 RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)
Comments