Skip to content

Instantly share code, notes, and snippets.

@specialunderwear
Created November 1, 2011 15:19
Show Gist options
  • Save specialunderwear/1330781 to your computer and use it in GitHub Desktop.
Save specialunderwear/1330781 to your computer and use it in GitHub Desktop.
metaclass for google.appengine.ext.db.Model with i18n properties.
from copy import deepcopy
from google.appengine.ext import db
import settings
class I18nModelMetaClass(db.PropertiedClass):
"""
Metaclass for adding language specific attributes to a
:class:`~google.appengine.ext.db.Model`
Make sure that you've got a settings.py with a ``LANGUAGES`` key and
a DEFAULT_LANGUAGE key::
DEFAULT_LANGUAGE = 'en'
LANGUAGES = ('en', 'nl', 'de')
usage::
from meta.i18n import I18nModelMetaClass
from google.appengine.ext import db
class SomeModel(db.Model):
__metaclass__ = I18nModelMetaClass
# tell I18nModelMetaClass which properties need to internationalized
i18n = ('title',)
title = db.StringProperty()
body = db.TextProperty()
now you will have a title for each language in LANGUAGES; ``title_en``,
``title_nl`` and ``title_de``.
"""
def __new__(cls, name, bases, dct, map_kind=True):
i18n = dct.pop('i18n')
i18n_attrs = {'_i18n':i18n}
for prop_name, prop in dct.items():
if prop_name in i18n:
for language in settings.LANGUAGES:
prop_i18n_name = '%s_%s' % (prop_name, language)
if language != settings.DEFAULT_LANGUAGE:
prop_cpy = deepcopy(prop)
# the other languages must not be required, otherwise I
# can not make a form that shows only fields for 1 language.
prop_cpy.required = False
i18n_attrs[prop_i18n_name] = prop_cpy
else:
i18n_attrs[prop_i18n_name] = prop
else:
i18n_attrs[prop_name] = prop
return db.PropertiedClass(name, bases, i18n_attrs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment