我希望将旧网址列表重定向到Django / Heroku应用程序中的新网址列表。
由于我使用的是Heroku,我不能只使用.htaccess
文件。
我看到rails有机架重写,但我还没有看到类似Django的内容。
答案 0 :(得分:5)
Django重定向应用程序,允许在数据库中存储重定向列表: https://docs.djangoproject.com/en/dev/ref/contrib/redirects/
此处还有一个通用的RedirectView:
https://docs.djangoproject.com/en/1.3/ref/class-based-views/#redirectview
最低级别是HttpResponseRedirect:
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponseRedirect
答案 1 :(得分:0)
来自301重定向的文档的示例:
urlpatterns = patterns('django.views.generic.simple',
('^foo/(?P<id>\d+)/$', 'redirect_to', {'url': '/bar/%(id)s/'}),
)
答案 2 :(得分:0)
您可以使用重定向。请检查以下代码。
from django.shortcuts import redirect
return redirect(
'/', permanent=True
)
对我有用。
答案 3 :(得分:0)
尽管接受的答案中提到的redirects app是一个非常不错的解决方案,但它还涉及针对每个404错误的数据库调用。我想避免这种情况,所以最终只能在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')),
]