Django – gettext_lazy not working in string interpolation/concatenation (inside list)

Question:

I have a dictionary of items with multiple properties.

from django.utils.translation import (
    gettext_lazy as _,
)

{"item1": {
          "labels": [
                      _("label1"), 
                      "this is" + _("translatethis") + " label2", 
                    ]

These items are then serialized in DRF.

The problem is that

_("label1") is being translated

but

"this is" + _("translatethis") + " label2" is not translated

I tried also string interpolation, fstring and .format but nothing worked. When serializer fetches labels, _("translatethis") is not a proxy object.

Is the only way to make this work surrounding whole strings in the gettext_lazy ?

Asked By: Milano

||

Answers:

The main problem is that _('translatethis') is not a string, but something that promises, when necessary, to be a string. When you however concatenate it with a string, it is time to keep its promise, and it thus presents a string, and it no longer can thus, when needed, check the active language.

An option might be to work with a lazy object, like:

from django.utils.functional import lazy


def text_join(*items):
    return ''.join(items)


text_join_lazy = lazy(text_join, str)

{
    'item1': {
        'labels': [
            _('label1'),
            text_join_lazy('this is ', _("translatethis"), ' label2'),
        ]
    }
}
Answered By: Willem Van Onsem
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.