Skip to content

Instantly share code, notes, and snippets.

@dokterbob
Created April 19, 2011 09:08
Show Gist options
  • Save dokterbob/927046 to your computer and use it in GitHub Desktop.
Save dokterbob/927046 to your computer and use it in GitHub Desktop.
Translations without using __dict__ :)
import logging, re
logger = logging.getLogger(__name__)
from django.utils.translation import get_language
LANGUAGE_CODE_RE = re.compile(r'_(?P<code>[a-z_]{2,5})$')
class TranslatableMixin(object):
""" Stolen from django-multilingual-model.
http://github.com/dokterbob/django-multilingual-model
"""
def __init__(self, *args, **kwargs):
super(TranslatableMixin, self).__init__(*args, **kwargs)
logger.debug('Init called.')
self._language = get_language()
def __getattr__(self, attr):
superclass = super(TranslatableMixin, self)
# If an attribute is simply available, don't look any further.
try:
return getattr(superclass, attr)
except AttributeError:
pass
assert self._language, \
'__init__ has not been called or something else went wrong. Make \
sure TranslatableMixin is the first base class.'
# Prevent recursion when a translation cannot be found
language_suffix = '_%s' % self._language
if attr.endswith(language_suffix):
raise AttributeError('Translation cannot be found for language %s' % self._language)
translated_field_name = attr + language_suffix
logger.debug('Normal field name %s not found, looking for %s.', \
attr, translated_field_name)
return getattr(self, translated_field_name)
def for_language(self, code):
"""Sets the language for the translation fields of this object"""
if code is not None and len(code) >= 2 and len(code) <= 5:
self._language = code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment