Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Django中如何通过URL模式重定向?_Python_Django_Django Urls - Fatal编程技术网

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

Python 在Django中如何通过URL模式重定向?,python,django,django-urls,Python,Django,Django Urls,我有一个基于Django的网站。我想将带有模式servertest的URL重定向到相同的URL,但servertest应替换为server test 例如,以下URL将被映射并重定向,如下所示: http://acme.com/servertest/ => http://acme.com/server-test/ http://acme.com/servertest/www.example.com => http:

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

例如,以下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 
我可以使用URL.py中的以下行获得第一个示例:

(“^servertest/$”,“重定向到”,{'url':“/server test/'}),

不确定如何为其他URL执行此操作,因此仅替换URL的servetest部分。

请尝试以下表达式:

   ('^servertest/', 'redirect_to', {'url': '/server-test/'}),
或者这个:
(“^servertest”,“重定向到”,{'url':“/server test/”}),

给定的URL可能包含字典样式的字符串格式,这些格式将根据URL中捕获的参数进行插值。因为关键字插值总是完成的(即使没有传入任何参数),所以URL中的任何“%”字符都必须写为“%%”,以便Python将它们转换为单百分比登录输出

(强烈强调我的观点。)

然后是他们的例子:

此示例从发出永久重定向(HTTP状态代码301) /foo//to/bar//:

从django.views.generic.simple import重定向到
urlpatterns=模式(“”,
(“^foo/(?P\d+/$”,将_重定向到,{'url':'/bar/%(id)s/')),
)
所以你可以看到,这只是一种简单明了的形式:

('^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),
(“^servertest/(?P.*)$”、“重定向到”、{'url':“/server test/%(路径)s}),
使用以下内容(针对Django 2.2更新):


在编辑之前,我遇到了一个错误:“redirect_to()为关键字参数“url”获取了多个值”,所以我尝试了Simeon Visser的答案,这个答案很有效。@TonyM:是的,你不能使用未命名的组;他们必须被命名。(我发现当我检查源代码时,它只是
**kwargs
,而不是
*args
)感谢您的澄清。您是否缺少
url()
-django说:
确保urlpatterns是url()实例的列表。提示:尝试使用url()而不是元组。
('^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),
re_path(r'^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),
path('servertest/<path:path>', 'redirect_to', {'url': '/server-test/%(path)s'}),