Translating formatted strings in Django does not work

I have a problem translating formatted strings in Django using django.utils.translations . Only strings without format ( %s or {} ) work.

My locale/en/LC_MESSAGES/django.po file:

 msgid "foo" msgstr "bar" #, python-format msgid "foo %s" msgstr "bar %s" #, python-format msgid "foo %(baz)s" msgstr "bar %(baz)s " #, python-brace-format msgid "foo {}" msgstr "bar {}" #, python-brace-format msgid "foo {baz}" msgstr "bar {baz}" 

The first line works:

 >>> from django.utils import translation >>> translation.activate('en') >>> translation.ugettext('foo') 'bar' 

But there is no rest:

 >>> translation.ugettext('foo %s' % 'bax') 'foo bax' >>> translation.ugettext('foo %(baz)s' % {'baz': 'bax'}) 'foo bax' >>> translation.ugettext('foo {}'.format('bax')) 'foo bax' >>> translation.ugettext('foo {baz}'.format(baz='bax')) 'foo bax' 

No, if I use ugettext_lazy , gettext or gettext_lazy - the same story, not the translated output.

Any idea why formatted strings don't work?

  • Django 1.11.3
  • Python 3.5.3
+5
source share
1 answer

You should format the lines returned by the ugettext, not the lines in the call. See Explanations below.

Instead:

 translation.ugettext('foo %s' % 'bax') translation.ugettext('foo %(baz)s' % {'baz': 'bax'}) translation.ugettext('foo {}'.format('bax')) translation.ugettext('foo {baz}'.format(baz='bax')) 

You need to do:

 translation.ugettext('foo %s') % 'bax' translation.ugettext('foo %(baz)s') % {'baz': 'bax'} translation.ugettext('foo {}').format('bax') translation.ugettext('foo {baz}').format(baz='bax') 

In your code, you are trying to get the translation of 'foo bax' every time, and you do not have this file in your translation file.

+5
source

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


All Articles