Django URL模式中的带参数国际化

2 投票
1 回答
1795 浏览
提问于 2025-04-18 12:33

我正在使用Django 1.6和Python 3.4,想要在参数中翻译网址。例如:
从:
/en/temperature/London/
变成:
/fr/température/Londres/
但这并没有成功。结果我得到的是 /fr/temperature/London/。在urls.py文件中,“temperature”是写死的,而“London”是参数city的值。treshold是可选的。
这个网址在没有参数的情况下翻译是正确的:/en/terms/变成/fr/mentions-légales/
每次我修改django.po文件后,我都会运行compilemessage命令,手动重启开发服务器,并清除浏览器缓存。请问哪里出错了?

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>

1 个回答

0

在你的urls.py文件中,你应该有这一行:

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

因为这是你在django.po文件中提到的那一行。在那里你会查找“temperature”,并把它替换成“température”。然后,

你还应该使用:

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

这会告诉Django也要翻译“London”。

你也可以使用两个网址:

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>

撰写回答