Ric*_*ckD 95 python django django-urls
如何将与我的任何其他URL不匹配的流量重定向回主页.我的urls.py看起来像,
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'^.*$', 'macmonster.views.home'),
)
Run Code Online (Sandbox Code Playgroud)
因为它是最后一个条目将所有"其他"流量发送到主页但我想通过HTTP 301或302重定向.
谢谢,
dmg*_*dmg 167
您可以尝试名为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')
)
Run Code Online (Sandbox Code Playgroud)
请注意如何为url在<url_to_home_view>您需要实际指定的URL.
permanent=False将返回HTTP 302,同时permanent=True将返回HTTP 301.
或者,您可以使用django.shortcuts.redirect
Kho*_*Phi 33
在Django 1.8中,这就是我的做法.
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))
Run Code Online (Sandbox Code Playgroud)
而不是使用url,你可以使用pattern_name,有点不干,并确保你改变你的网址,你也不必改变重定向.
bom*_*mbs 11
其他方法工作正常,但您也可以使用旧的django.shortcut.redirect.
下面的代码取自这个答案。
在 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')),
]
Run Code Online (Sandbox Code Playgroud)
Bla*_*ett 10
如果你像我一样被困在django 1.2上并且RedirectView不存在,那么添加重定向映射的另一种以路径为中心的方法是使用:
(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}),
Run Code Online (Sandbox Code Playgroud)
您还可以在比赛中重新路由所有内容.这在更改应用程序的文件夹但希望保留书签时非常有用:
(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}),
Run Code Online (Sandbox Code Playgroud)
这比django.shortcuts.redirect更好,如果你只是想修改你的url路由并且没有访问.htaccess等等(我在Appengine上,而app.yaml不允许在那个级别进行url重定向,就像的.htaccess).
另一种方法是使用HttpResponsePermanentRedirect,如下所示:
在view.py中
def url_redirect(request):
return HttpResponsePermanentRedirect("/new_url/")
Run Code Online (Sandbox Code Playgroud)
在url.py中
url(r'^old_url/$', "website.views.url_redirect", name="url-redirect"),
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85424 次 |
| 最近记录: |