Django URL Redirect
The other methods work fine, but you can also use the good old django.shortcut.redirect
.
The code below was taken from this answer.
In Django 2.x:
from django.shortcuts import redirect
from django.urls import path, include
urlpatterns = [
# this example uses named URL 'hola-home' from app named hola
# for more redirect's usage options: https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/
path('', lambda request: redirect('hola/', permanent=True)),
path('hola/', include('hola.urls')),
]
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')
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.