Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading