Reputation: 2181
I would like to determine, if there's a translation to current language for a given string. I'd like to write something like:
if not translation_available("my string"):
log_warning_somewhere()
I didn't find anything appropriate. The ugettext
function just returns the translation or the original string (if the translation isn't available) but without any option to determine if the translation is there or isn't.
Thanks.
Upvotes: 10
Views: 2684
Reputation: 71
Szymon's solution worked for me after a minor change:
from django.utils.translation import trans_real
def custom_gettext(msg):
# Returns None when a data translation is not found
return trans_real.catalog()._catalog.get(msg) # noqa
if custom_gettext("my string") is None:
log_something()
Upvotes: 0
Reputation: 383
For anyone looking for a hacky solution:
from django.utils.translation import trans_real
def custom_gettext(msg):
# Returns None when a data translation is not found
return trans_real._active.value._catalog.get(msg) # noqa
if custom_gettext("my string") is None:
log_something()
Upvotes: 4
Reputation: 6825
You can use polib for that: https://bitbucket.org/izi/polib/wiki/Home
Something along those (untested) lines of code:
import polib
po = polib.pofile('path/your_language.po')
text == 'Your text'
is_translated = any(e for e in po if e.msgid == text and (not e.translated() or 'fuzzy' in e.flags) and not e.obsolete)
This will give True when an active translation is available. 'e.translated()' alone returns True for both, fuzzy and/or obsolete phrases, too.
Upvotes: 2
Reputation: 599856
Since, as you say, ugettext will return the original string if no translation is available, can't you just compare the returned value with the original to see if they're identical?
Upvotes: 0