from django.db.models.base import ModelBase from django.db.models.base import Model from django.db import models from django.conf import settings # Returns class object from a specified module def getclass(classname, modulename): from_module = __import__(modulename, globals(), locals(), classname) return getattr(from_module, classname) class I18NBase(ModelBase): def __new__(cls, name, bases, attrs): try: if I18NModel in bases: attr_meta = attrs.pop('Meta', None) # Find out if `i18n_common_model` is defined in `class Meta`, # and use that. Otherwise, use this class name -4 chars: common_classname = getattr(attr_meta, 'i18n_common_model', name[:-4]) I18NCommonModel = getclass(common_classname, attrs['__module__']) attrs['i18n_common'] = models.ForeignKey(I18NCommonModel) attrs['lang'] = models.CharField(max_length = 5, choices = settings.LANGUAGES) except NameError: pass return ModelBase.__new__(cls, name, bases, attrs) class I18NModel(Model): __metaclass__ = I18NBase class Meta: abstract = True