2014-07-08 54 views
2

我正在使用Django 1.6和Python 3.4。我想在參數中翻譯網址。例如:
/EN /溫度/倫敦/
到:
/FR /溫度/倫敦/
,但它不工作。相反,我獲得/ fr /溫度/倫敦/。在urls.py中,「溫度」是硬編碼的,「倫敦」是參數值citytreshold是可選的。 這個網址,沒有參數,翻譯正確:/ en/terms/to/fr/mentions-légales/
在django.po每次更改後,我運行compilemessage命令,手動重新啓動開發服務器並刷新瀏覽器緩存。哪裏不對?Django具有參數的url模式國際化

urls.py: 
from django.conf.urls.i18n import i18n_patterns 
from django.utils.translation import ugettext_lazy as _ 

urlpatterns += i18n_patterns('foo.views', 
    url(_(r'^terms/$'), 'terms', name="terms"), 
    url(_(r'^temperature/%(city)s(?:/(%(treshold)s))?/$') %{'city': city, 'treshold': treshold}, 'temperature', name="temperature"), 
) 

django.po 
#: /urls.py:X 
#, python-format 
msgid "^temperature/%(city)s(?:/(%(treshold)s))?/$" 
msgstr "^température/%(city)s(?:/(%(treshold)s))?/$" 

msgid "London" 
msgstr "Londres" 

msgid "^terms/$" 
msgstr "^mentions-légales/$" 

{% load i18n %} 
<a href="{% url 'temperature' city="London" %}">Link name</a> 

回答

0

在你的urls.py你應該有一行:

url(_(r'^temperature/%(city)s(?:/(%(treshold)s))?/$') %{'city': city, 'treshold': treshold}, 'temperature', name="temperature"), 

因爲這是你指的是你的django.po行。在那裏,你搜索的溫度和隨溫度替換它,然後

此外,您應該使用:

{% load i18n %} 
<a href="{% url 'temperature' city=_("London") %}">Link name</a> 

這將告訴Django以及翻譯倫敦。

您還可以使用2個網址:

url(_(r'^temperature/%(city)s(?:/(%(treshold)s))?/$') %{'temperature': temperature, 'treshold': treshold}, 'temperature', name="temperature"), 
url(_(r'^témperature/%(city)s(?:/(%(treshold)s))?/$') %{'temperature': temperature, 'treshold': treshold}, 'temperature', name="témperature"), 

,並在你的HTML,您可以使用:

<a href="{% url _('temperature') city=_("London") %}">Link name</a> 
+0

你是對的:在urls.py 「溫度」,而不是 「溫度」;我剛剛編輯了我的第一篇文章。添加_(),但在「city =」之後沒有空格,我獲得/ fr/temperature/Londres /:只有「溫度」有待翻譯。 – jk9

+0

這與正則表達式有關。我認爲你的django.po目前無法處理正則表達式,並進行字符串比較。由於閾值部分不存在,因此它與字符串「^ temperature /%(city)s(?:/(%(treshold)s))/ $」 – gaw

+0

編輯了我的答案,併爲此解決了 – gaw