简体   繁体   English

如何在Django中通过URL模式重定向?

[英]How do I redirect by URL pattern in Django?

I have a Django based website. 我有一个基于Django的网站。 I would like to redirect URLs with the pattern servertest in them to the same URL except servertest should be replaced by server-test . 我想将其中带有servertest模式的URL重定向到相同的URL,除了servertest应该被server-test替换。

So for example the following URLs would be mapped be redirected as shown below: 因此,例如,将映射以下URL重定向,如下所示:

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 

I can get the first example working using the following line in urls.py: 我可以使用urls.py中的以下行来获取第一个示例:

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

Not sure how to do it for the others so only the servetest part of the URL is replaced. 不知道如何为其他人这样做,所以只更换URL的servetest部分。

It's covered in the docs. 它包含在文档中。

The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. 给定的URL可能包含字典样式的字符串格式,它将根据URL中捕获的参数进行插值。 Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output. 因为关键字插值总是完成 (即使没有传入参数),URL中的任何“%”字符都必须写为“%%”,以便Python将它们转换为输出上的单个百分号。

(Strong emphasis mine.) (非常强调我的。)

And then their examples: 然后是他们的例子:

This example issues a permanent redirect (HTTP status code 301) from /foo/<id>/ to /bar/<id>/: 此示例从/ foo / <id> /发出永久重定向(HTTP状态代码301)到/ bar / <id> /:

 from django.views.generic.simple import redirect_to urlpatterns = patterns('', ('^foo/(?P<id>\\d+)/$', redirect_to, {'url': '/bar/%(id)s/'}), ) 

And so you see that it's just the nice straightforward form: 所以你看到它只是一个很好的直截了当的形式:

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

Use the following (updated for Django 2.2): 使用以下(为Django 2.2更新):

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

It takes zero or more characters after servertest/ and places them after /server-test/ . 在servertest /之后它需要零个或多个字符,并将它们放在/ server-test /之后。

Try this expression : 试试这个表达式:

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

or this one: 或者这个:
('^servertest', 'redirect_to', {'url': '/server-test/'}), ('^ servertest','redirect_to',{'url':'/ server-test /'}),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM