Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

lookup translation

View language_utils.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
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]
 
else:
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)
 
else:
q = obj.translations.filter(
languagecode__istartswith = language_code)
 
if q.count() > 0:
trans = None
if version > -1:
trans = q.order_by('-version')[0]
else:
# 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
break
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
Something went wrong with that request. Please try again.