Django URL重定向

编程入门 行业动态 更新时间:2024-10-08 06:21:29
本文介绍了Django URL重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何将与任何其他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重定向

本文发布于:2023-10-10 18:27:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479377.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重定向   Django   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!