2012-03-29 29 views
1

我有一個基於Django的網站。我想重定向其中的模式servertest的URL到相同的URL,除了servertest應該被服務器測試替換。如何在Django中重寫此URL?

因此,例如,以下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 

我能得到第一個例子中使用下面的行urls.py工作:

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

不確定如何爲別人做到這一點,所以只有URL的servetest部分被替換。

回答

2

使用以下:

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

它採用零個或多個字符在servertest之後,並將它們放在/ server-test /之後。

+0

謝謝你的工作。 – TonyM 2012-03-29 10:23:21

0

嘗試這個表達式:

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

或這一個:
( '^ servertest', 'redirect_to的',{ 'URL': '/ servertest /'}),

2

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. 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.

(強重點煤礦。)

然後將自己的例子:

This example issues a permanent redirect (HTTP status code 301) from /foo/<id>/ to /bar/<id>/:

from django.views.generic.simple import redirect_to 

urlpatterns = patterns('', 
    ('^foo/(?P<id>\d+)/$', redirect_to, {'url': '/bar/%(id)s/'}), 
) 

所以你看到,這只是漂亮的簡單形式:

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

在你編輯之前,我得到這個錯誤:「redirect_to()爲關鍵字參數'url'獲得了多個值」,所以我嘗試了Simeon Visser的工作答案。 – TonyM 2012-03-29 10:22:11

+0

@TonyM:是的,你不能使用未命名的組;他們必須被命名。 (我發現,當我檢查源代碼時,它只是'** kwargs',而不是'* args'。) – 2012-03-29 12:58:58

+0

感謝您的澄清。 – TonyM 2012-03-30 15:08:55