Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
lookup translation
from django.core.exceptions import ImproperlyConfigured
from django.utils.safestring import mark_safe
from django.utils.translation import get_language
import logging
import re
UNSET = object()
def lookup_translation(obj, attr, language_code=None, version=-1):
"""Get a translated attribute by language.
If specific language isn't found, returns the attribute from the base object.
if not language_code:
language_code = get_language()
if not hasattr(obj, '_translationcache'):
obj._translationcache = {}
short_code = language_code
pos = language_code.find('_')
if pos > -1:
short_code = language_code[:pos]
pos = language_code.find('-')
if pos > -1:
short_code = language_code[:pos]
trans = None
has_key = obj._translationcache.has_key(language_code)
if has_key:
if obj._translationcache[language_code] == None and short_code != language_code:
return lookup_translation(obj, attr, short_code)
if not has_key:
q = obj.translations.filter(
languagecode__iexact = language_code)
if q.count() == 0:
obj._translationcache[language_code] = None
if short_code != language_code:
return lookup_translation(obj, attr, language_code=short_code, version=version)
q = obj.translations.filter(
languagecode__istartswith = language_code)
if q.count() > 0:
trans = None
if version > -1:
trans = q.order_by('-version')[0]
# try to get the requested version, if it is available,
# else fallback to the most recent version
fallback = None
for t in q.order_by('-version'):
if not fallback:
fallback = t
if t.version == version:
trans = t
if not trans:
trans = fallback
obj._translationcache[language_code] = trans
if not trans:
trans = obj._translationcache[language_code]
if not trans:
trans = obj
val = getattr(trans, attr, UNSET)
if trans != obj and (val in (None, UNSET)):
val = getattr(obj, attr)
return mark_safe(val)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment