garg10may
garg10may

Reputation: 6179

Django Translation - Translate dynamic strings

We are using Django as our backend REST API server. I am looking to translate text being sent as push notifications to our app. I am new to translations.

The text resides in a config file and varies for each user.

NOTIFICATION_TEXT = {
  'access_request': '%(user_name)s has requested to access your document %(story_name)s, please review '}

I saw the google translate feature and it perfectly translates if given the final sentence understanding the user_name and story_name are constant. I was looking for a similar magic band functionality in Django where I can just wrap final message before sending to the user in the locale received in the Accept-language header of the REST call. But this doesn't seem possible.

As I understand I would need to pre-mark the text which needs to be translated with ugettext and define language and middleware settings. Then generate locale specific files using

django-admin makemessages -l de

and then in the generated django.po file for that specific locale gives the translated text manually for Django to refer.

But I am stuck how to mark given my message is dynamic, inside a dic. Or is there another way around?

Edit:

The data is accessed as below

data['msg'] = settings.NOTIFICATION_TEXT['access_request'] % \
              dict(
                user_name=get_user_name(sender),
                story_name=story.story_name
              )

Upvotes: 2

Views: 3552

Answers (1)

user2390182
user2390182

Reputation: 73460

You have to apply the appropriate translation function to the message before inserting the dynamic context, in this case (module level, I assume) that would be one of the lazy ones:

from django.utils.translation import ugettext_lazy as _

NOTIFICATION_TEXT = {
  'access_request': _('%(user_name)s has requested to access your document %(story_name)s, please review ')
}

makemessages -l de will then create an entry in the locale's django.po:

msgid "%(user_name)s has requested to access your document %(story_name)s, please review "
msgstr ""

The translated string must contain all the dynamic placeholders unchanged:

msgid "%(user_name)s has requested to access your document %(story_name)s, please review "
msgstr "%(user_name)s hat Zugang zu Ihrem Dokument %(story_name)s beantragt, bitte überprüfen Sie "

It is important to apply the (user_name, story_name) context to the message after applying the translation function, which your architecture pretty much already enforces at this time:

message = NOTIFICATION_TEXT['access_request'] % {'user_name': 'foo', 'story_name': 'bar'}

Upvotes: 4

Related Questions