Django URL重定向 [英] Django URL Redirect
问题描述
如何将与任何其他URL不匹配的流量重定向到主页。
我的urls.py看起来像,
How can I redirect traffic that doesnt match any of my other URLs back to the home page. My urls.py looks like,
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'),
)
由于最后一个条目发送所有其他流量到主页,但我想通过HTTP 301或302重定向。
As it stands the last entry sends all "other" traffic to the home page but I want to redirect via either a HTTP 301 or 302.
谢谢,
推荐答案
您可以尝试基于类的视图,名为 RedirectView
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')
)
请注意 url
c>< url_to_home_view> 您需要实际指定网址。
Notice how as url
in the <url_to_home_view>
you need to actually specify the url.
permanent = False
将返回HTTP 302,而 permanent = True
将返回HTTP 301。
permanent=False
will return HTTP 302, while permanent=True
will return HTTP 301.
或者,您可以使用 django.shortcuts.redirect
这篇关于Django URL重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!