I'm looking for a sane way to get to the untranslated content of a ugettext_lazy
ied 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_lazy
ied string and the code that accesses it are miles appart.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With