How do I accomplish a simple redirect (e.g. cflocation
in ColdFusion, or header(location:http://)
for PHP) in Django?
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.
page_path = define in urls.py
def deletePolls(request):
pollId = deletePool(request.GET['id'])
return HttpResponseRedirect("/page_path/")
If you want to redirect a whole subfolder, the url
argument in RedirectView is actually interpolated, so you can do something like this in urls.py
:
from django.conf.urls.defaults import url
from django.views.generic import RedirectView
urlpatterns = [
url(r'^old/(?P<path>.*)$', RedirectView.as_view(url='/new_path/%(path)s')),
]
The ?P<path>
you capture will be fed into RedirectView
. This captured variable will then be replaced in the url
argument you gave, giving us /new_path/yay/mypath
if your original path was /old/yay/mypath
.
You can also do ….as_view(url='…', query_string=True)
if you want to copy the query string over as well.
With Django version 1.3, the class based approach is:
from django.conf.urls.defaults import patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^some-url/$', RedirectView.as_view(url='/redirect-url/'), name='some_redirect'),
)
This example lives in in urls.py