Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating formatted strings in Django not working

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

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}"

First string is working:

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

But rest is not:

>>> 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 mater if I use ugettext_lazy, gettext or gettext_lazy - same story, not translated output.

Any idea why formatted strings are not working?

  • Django 1.11.3
  • Python 3.5.3
like image 437
bns Avatar asked Jul 06 '17 19:07

bns


People also ask

How do I translate text in Django?

Use the function django. utils. translation. gettext_noop() to mark a string as a translation string without translating it.

What is Gettext_lazy in Django?

gettext_lazy is a callable within the django. utils. translation module of the Django project.

Which Python operator is used for string formatting?

The modulo % is also known as the “string-formatting operator”.


1 Answers

You should format the strings returned by ugettext and not the strings in the call. See clarification below.

Instead of:

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' each time, and you don't have that msgid in your translation file.

like image 116
Enric Calabuig Avatar answered Sep 27 '22 22:09

Enric Calabuig