Django URL Redirect
Solution 1:
You can try the Class Based View called RedirectView
from django.views.generic.base import RedirectView
urlpatterns = 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_path
re_path(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
Solution 2:
In Django 1.8, this is how I did mine.
from django.views.generic.base import RedirectView
url(r'^$', views.comingSoon, name='homepage'),
# whatever urls you might have in here
# make sure the 'catch-all' url is placed last
url(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.