【问题标题】:How to Redirect URLs to a certain URL Django Regex如何将 URL 重定向到某个 URL Django Regex
【发布时间】:2021-10-20 20:48:17
【问题描述】:

在我的 URLs.py 中,我正在这样设置我的 URL

url(r'^mobile/$', views.mobile, name='mobile')

导航到 localhost:8000/mobile 可以正常工作,但如果输入 URL:localhost:8000/mobile/hello/world/234234hjhf8sc3,它应该重定向到 localhost:8000/mobile 但是这不会发生,因为我的正则表达式不正确(我不确定)

我该怎么做/正确的正则表达式是什么?

另一个例子是localhost:8000/mobile/send/help/as792lp 应该重定向到 localhost:8000/mobile

【问题讨论】:

    标签: python django string redirect


    【解决方案1】:

    您可以使用RedirectView [Django-doc] 将任何以mobile/ 开头的URL 重定向到mobile 视图:

    from django.urls import reverse_lazy
    from django.views.generic.base import RedirectView
    
    url(r'^mobile/$', views.mobile, name='mobile')
    url(r'^mobile/.+$', RedirectView.as_view(url=reverse_lazy('mobile')))

    注意:截至url(…) [Django-doc] 是 不推荐使用 re_path(…) [Django-doc]。 此外,路径转换器还引入了一种新的路径语法:你 为此使用path(…) [Django-doc]

    【讨论】:

    • 这会重定向视图,但将 URL 本身重定向到“/mobile”不是更好的方法吗?
    • @AngelaRubchinksy:两者有什么区别。如果你访问像/mobile/hello/world/234234hjhf8sc3这样的URL,它会返回一个HTTP 302(重定向)到/mobile/,然后触发另一个视图来呈现内容。
    • 使用你的方法,我得到一个 django.urls.exception.NoReverseMatch 错误。似乎找不到“移动”的反面,它不是有效的视图或模式名称
    • @AngelaRubchinksy:您是否在 `urls.py 中指定了 app_name
    • @AngelaRubchinksy:那你应该把它改成reverse_lazy('development:mobile')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2013-03-15
    • 2019-08-15
    • 2018-09-19
    相关资源
    最近更新 更多