views:

8550

answers:

4

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) in php)?

+57  A: 

It's simple:

from django.http import HttpResponseRedirect

def myview(request):
    ...
    return HttpResponseRedirect("/path/")

More info in the official Django docs

Baishampayan Ghose
+1: Quote the docs.
S.Lott
+17  A: 

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 HttpResponsePermanentRedirect

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

Teddy
+4  A: 

Since Django 1.1, you can also use the simpler redirect shortcut:

from django.shortcuts import redirect

def myview(request):
    return redirect('/path')

It also takes an optional permanent=True keyword argument.

Kennu
+4  A: 

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_to

urlpatterns = patterns('',
    # static media (development only)    
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

See http://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-simple-redirect-to for more advanced examples

Carles Barrobés