Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings won't be translated in Django using format function available in Python 2.7

Does the new and recommended way to format strings available in Python 2.7 using format result in a non translated string in Django?

The strings are in the .po file, translated, but it won't be translated on the website. For example:

from django.utils.translation import ugettext as _

website_name = "Stackoverflow"
title = _(u"{sitename} is a good website".format(sitename=website_name))

The .po file after translating the string looks like this:

#: path/to/file.py:4
msgid "{sitename} is a good website"
msgstr "{sitename} ist eine gute Website"

After running django-admin.py compilemessages and restarting the webserver, on the processed HTML page it is still in english, while all the other strings are being translated. Furthermore, while all strings using format are not translated, strings formatted using the % operator are translated as expected. It is also not a gettext/ugettext issue, as the problem is the same with both functions.

like image 236
Iodnas Avatar asked Jul 22 '12 17:07

Iodnas


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 format () function in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

How do I format a string to print in Python?

There are several ways to format output. To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.

How do you use %d strings in Python?

The %d operator is used as a placeholder to specify integer values, decimals, or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values.


1 Answers

compilemessages sees the string as "{sitename} is a good website", but when the app is running the string is actually e.g. "MySite is a good website", which of course doesn't have a translation. You must translate the bare string first, and then you can perform template operations on it.

like image 126
Ignacio Vazquez-Abrams Avatar answered Oct 05 '22 04:10

Ignacio Vazquez-Abrams