Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access untranslated content of Django's ugettext_lazy

I'm looking for a sane way to get to the untranslated content of a ugettext_lazyied string. I found two ways, but I'm not happy with either one:

the_string = ugettext_lazy('the content')
the_content = the_string._proxy____args[0] # ewww!

or

from django.utils.translation import activate, get_language
from django.utils.encoding import force_unicode

the_string = ugettext_lazy('the content')
current_lang = get_language()
activate('en')
the_content = force_unicode(the_string)
activate(current_lang)

The first piece of code accesses an attribute that has been explicitly marked as private, so there is no telling how long this code will work. The second solution is overly verbose and slow.

Of course, in the actual code, the definition of the ugettext_lazyied string and the code that accesses it are miles appart.

like image 825
Benjamin Wohlwend Avatar asked Feb 28 '11 15:02

Benjamin Wohlwend


2 Answers

This is the better version of your second solution

from django.utils import translation

the_string = ugettext_lazy('the content')
with translation.override('en'):
    content = unicode(the_string)
like image 156
Taha Jahangir Avatar answered Sep 28 '22 03:09

Taha Jahangir


Another two options. Not very elegant, but not private api and is not slow.

  • Number one, define your own ugettext_lazy:

    from django.utils import translation
    
    def ugettext_lazy(str):
        t = translation.ugettext_lazy(str)
        t.message = str
        return t
    
    >>> text = ugettext_lazy('Yes')
    >>> text.message
    "Yes"
    >>> activate('lt')
    >>> unicode(text)
    u"Taip"
    >>> activate('en')
    >>>> unicode(text)
    u"Yes"
    
  • Number two: redesign your code. Define untranslated messages separately from where you use them:

    gettext = lambda s: s
    some_text = gettext('Some text')
    
    lazy_translated = ugettext_lazy(text)
    untranslated = some_text
    
like image 20
Ski Avatar answered Sep 28 '22 05:09

Ski