How to return a lazy translation object with placeholders?

In my Django v1.6.5 project running on Python v2.7.x, I have a model that returns its configuration as a string. I need the returned string as a gettext_lazy object, so I can evaluate it in any language that is required later.

from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _, string_concat
...

class MyModel(models.Model):

    key = models.CharField(...)
    value = models.CharField(...)

    @property
    def config_str(self):
        return _('some configuration')

In these scenarios, this works great:

  • Static string: (see above) - it works!
  • String concatenation: return string_concat(self.key, _(' equals '), self.value)- works!

What doesn't work, uses gettext_lazy with placeholders, a la:

return _('"%(key)s" equals "%(value)s"' % {key: self.key, value: self.value})

or using the .format () mechanism:

return _('"{key}" equals "{value}"').format(key=self.key, value=self.value)

When I do this, my .po file contains:

#, python-format
msgid ""%(key)s" equals "%(value)s"" or
msgid "«{key}» equals «{value}»"

but even when I fill this Eg .:

msgstr "«%(key)s» est égal à «%(value)s»" or
msgstr "«{key}» est égal à «{value}»"

, , , . , , EN . , "foo" "bar". , EN, FR (). , . , , , gettext "foo" "bar" () , - .

, () :

return _('"{key}" equals "{value}"'.format(key=self.key, value=self.value))

, , . =/

string_concat(), , .

, placeholders gettext_lazy.

. django: , a), , b) gettext, gettext_lazy.

+4
2

, - (, ​​devang: dev. Florian Apolloner AKA "apollo13" ).

, :

from django.utils import six
from django.utils.functional import lazy

class MyModel(models.Model):

    key = models.CharField(...)
    value = models.CharField(...)

    @property
    def configuration_string(self):

        def wrapper():
            return _('"{key}" equals "{value}"').format(
                key=self.key,
                value=self.value
            )

        return lazy(
            wrapper,
            six.text_type
        )

, , :

from django.utils.encoding import force_text

config = my_model_instance.configuration_string
# NOTE: Evaluate the lazy function wrapper inside the force_text()
config_str = force_text(config())

, , , configuration_string, , , , :

import types
from django.utils.encoding import force_text
from django.functional import Promise

config = my_model_instance.configuration_string

if isinstance(config, types.FunctionType):
    config_str = force_text(config())
elif isinstance(config, Promise):
    config_str = force_text(config)
else:
    config_str = config

Apollo13 !

+2

, , gettext_noop gettext_lazy .

0

Source: https://habr.com/ru/post/1545466/


All Articles