如何在Django中通过URL模式重定向? [英] How do I redirect by URL pattern in Django?

查看:91
本文介绍了如何在Django中通过URL模式重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于Django的网站。我想将其中带有模式 servertest 的URL重定向到相同的URL,除了 servertest 应该替换为 server-test

I have a Django based website. I would like to redirect URLs with the pattern servertest in them to the same URL except servertest should be replaced by server-test.

例如,以下URL将被映射,如下所示:

So for example the following URLs would be mapped be redirected as shown below:

http://acme.com/servertest/                        =>  http://acme.com/server-test/ 

http://acme.com/servertest/www.example.com         =>  http://acme.com/server-test/www.example.com

http://acme.com/servertest/www.example.com:8833    =>  http://acme.com/server-test/www.example.com:8833 

我可以得到第一个使用urls.py中的以下行的示例:

I can get the first example working using the following line in urls.py:

    ('^servertest/$', 'redirect_to', {'url': '/server-test/'}),

不确定其他方法,因此仅替换URL的servetest部分。

Not sure how to do it for the others so only the servetest part of the URL is replaced.

推荐答案

使用以下(已针对Django 2.2更新):

Use the following (updated for Django 2.2):

re_path(r'^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),

servertest / 之后需要零个或多个字符,并将它们放在 / server-test / 之后。

It takes zero or more characters after servertest/ and places them after /server-test/.

或者,您可以使用新的 path 函数,该函数涵盖简单情况下的URL模式,而无需使用正则表达式(并且在新版本中更受欢迎) Django):

Alternatively, you can use new path function that covers simple cases url patterns without using regex (and it is preferred in new versions of Django):

path('servertest/<path:path>', 'redirect_to', {'url': '/server-test/%(path)s'}),

这篇关于如何在Django中通过URL模式重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆