Reputation: 83
I'm looking to redirect a list of old URLs to a list of new URLs in a Django/Heroku app.
Since I'm using Heroku, I can't just use an .htaccess
file.
I see that rails has rack-rewrite, but I haven't seen anything like that for Django.
Upvotes: 7
Views: 8965
Reputation: 8228
While the redirects app mentioned in the accepted answer is a pretty nice solution, it also involves a database call for every 404 error. I wanted to avoid this so ended up just manually implementing this in a URL conf.
"""redirects.py that gets included by urls.py"""
from django.urls import path, reverse_lazy
from django.views.generic.base import RedirectView
def redirect_view(slug):
"""
Helper view function specifically for the redirects below since they take
a kwarg slug as an argument.
"""
return RedirectView.as_view(
url=reverse_lazy('app_name:pattern_name', kwargs={'slug': slug}),
permanent=True)
urlpatterns = [
path('example-redirect/', redirect_view('new-url')),
]
Upvotes: 0
Reputation: 4306
You can use redirect. Please check below code.
from django.shortcuts import redirect
return redirect(
'/', permanent=True
)
It worked for me.
Upvotes: 3
Reputation: 670
Try redirect_to
Example from the docs for a 301 redirect:
urlpatterns = patterns('django.views.generic.simple',
('^foo/(?P<id>\d+)/$', 'redirect_to', {'url': '/bar/%(id)s/'}),
)
Upvotes: 1
Reputation: 783
Django has redirects app, which allows to store redirects list in database: https://docs.djangoproject.com/en/dev/ref/contrib/redirects/
Also here a generic RedirectView:
https://docs.djangoproject.com/en/1.3/ref/class-based-views/#redirectview
And the lowest level is HttpResponseRedirect:
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponseRedirect
Upvotes: 6