Search code examples
djangodjango-urlsdjango-i18n

Django: international routes


My routes are like that:

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

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]
urlpatterns += i18n_patterns(
    url(r'^{0}/'.format(_('produits')),
        include('produits.urls', namespace="produits")
        ),
)

I thought the format(_('produits')) would adapt itself, so I've made two .po files:

makemessages -l en
makemessages -l fr

and in the english .po file, i've changed that:

#: .\pyweb\urls.py:31
msgid "produits"
msgstr "products"

I've then restarted the webserver, and I still have:

  • http://localhost:8000/en/produits/ -> ok
  • http://localhost:8000/en/products/ -> page not found

What am I doing wrong?


Solution

  • When you use .format(), the lazily translated string is evaluated immediately at import time. You want a single pattern with a lazily translated string as the regex. This means you have to translate the whole regex.

    urlpatterns = [
        url(r'^admin/', include(admin.site.urls)),
    ]
    urlpatterns += i18n_patterns(
        url(_(r'^produits/'),
            include('produits.urls', namespace="produits")
            ),
    )
    

    This way, the regex pattern will change depending on the current language for the request, as the lazy translation is only evaluated when you use resolve() or reverse().

    You have to add the complete regex to your .po files:

    #: .\pyweb\urls.py:31
    msgid "^produits/"
    msgstr "^products/"