Search code examples
djangointernationalizationdjango-i18n

Django translations of path **kwargs in urls.py?


How can I translate the values passed to **kwargs within the urls.py file in Django, based on the language selected by the user? Translations in templates are working, and the language is determined by the Accept-Language header set by the Nginx server. However, this language selection doesn't have any effect within the urls.py file, and instead is determined by LANGUAGE_CODE in settings.py file.

Here is an example urls.py:

from django.urls import path
from main.views import SharedIndexView
from django.utils.translation import pgettext

app_name = 'some_site'

urlpatterns = [
    path('', SharedIndexView.as_view(), {'SITE_SEO_title':  pgettext('home', 'SITE_SEO_title')}
]

My question is, how can I translate the **kwargs values passed to the path method according to the user's selected language, and not according to LANGUAGE_CODE? Is there a different approach I could use to achieve this?


Solution

  • The main problem is that pgettext is eagerly: it translates text when it is given that. So here when it interprets urls.py (for the first time), so before the moment the server starts accepting requests.

    We need to postpone the translation process until we need the string, and thus then look for the language context. This is why pgettext_lazy is used:

    from django.urls import path
    from django.utils.translation import pgettext_lazy
    from main.views import SharedIndexView
    
    app_name = 'some_site'
    
    urlpatterns = [
        path(
            '',
            SharedIndexView.as_view(),
            {'SITE_SEO_title': pgettext_lazy('home', 'SITE_SEO_title')},
        )
    ]

    This will thus return an object that, when needed, translate the string.