Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django translation: add custom translation

I have an application where users can fill a text field. I would like "try" to translate it if the string that the user entered is in the .po translation files.

So in one of my detail views, I did something like:

class InterrogationDetailView(generic.DetailView):
    model = Interrogation

    def get_context_data(self, **kwargs):
        context = super(InterrogationDetailView, self)\
            .get_context_data(**kwargs)
        if self.object is not None:
            context[u'translated_word'] = {
                u'description': _(self.object.description),
            }
        return context

That's nice, it seems to work. So it searches in the .po files. So I'd like to add sentences, or words on my own in those .po files. When I try to add one translation that is not in my source files, when I call makemessages I get them commented like:

#~ msgid "I'm a test"
#~ msgstr "Godsmack - Cryin' like a b"

How to solve this? And if I'm not doing this the right way (I've read a lot about django translation), what is the way to go?

like image 653
Olivier Pons Avatar asked Nov 10 '22 00:11

Olivier Pons


1 Answers

Django documentation mentions that makemessages is not capable of extracting translations for computed values, as happens in your example.

In order to have translations for strings that you retrieve from somewhere else you have to have them in your code as string literals. This can be achieved by the way @psychok7 suggests, creating a separate .py listing all those strings.

One way to automate this could be to write your custom django-admin command that will retrieve strings to be translated from database and put them into some file, locatable by makemessages, e.g. .txt with translation tags.

like image 96
dmvrtx Avatar answered Nov 15 '22 04:11

dmvrtx