Django URL Redirect Django URL Redirect python python

Django URL Redirect


You can try the Class Based View called RedirectView

from django.views.generic.base import RedirectViewurlpatterns = patterns('',    url(r'^$', 'macmonster.views.home'),    #url(r'^macmon_home$', 'macmonster.views.home'),    url(r'^macmon_output/$', 'macmonster.views.output'),    url(r'^macmon_about/$', 'macmonster.views.about'),    url(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index'))

Notice how as url in the <url_to_home_view> you need to actually specify the url.

permanent=False will return HTTP 302, while permanent=True will return HTTP 301.

Alternatively you can use django.shortcuts.redirect

Update for Django 2+ versions

With Django 2+, url() is deprecated and replaced by re_path(). Usage is exactly the same as url() with regular expressions. For replacements without the need of regular expression, use path().

from django.urls import re_pathre_path(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')


In Django 1.8, this is how I did mine.

from django.views.generic.base import RedirectViewurl(r'^$', views.comingSoon, name='homepage'),# whatever urls you might have in here# make sure the 'catch-all' url is placed lasturl(r'^.*$', RedirectView.as_view(pattern_name='homepage', permanent=False))

Instead of using url, you can use the pattern_name, which is a bit un-DRY, and will ensure you change your url, you don't have to change the redirect too.


If you are stuck on django 1.2 like I am and RedirectView doesn't exist, another route-centric way to add the redirect mapping is using:

(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}),  

You can also re-route everything on a match. This is useful when changing the folder of an app but wanting to preserve bookmarks:

(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}),  

This is preferable to django.shortcuts.redirect if you are only trying to modify your url routing and do not have access to .htaccess, etc (I'm on Appengine and app.yaml doesn't allow url redirection at that level like an .htaccess).