Django中的内容翻译,与South兼容

时间:2011-08-02 16:04:36

标签: django localization internationalization django-south

我正在寻找一个在Django中拥有可翻译数据库字段的解决方案,该解决方案需要与South兼容。

我已找到django-transmetatransdb。只有后者似乎与南方兼容,但我不确定。此外,transdb值在数据库中看起来不太好(客户实际关心的事情)。

有没有人使用过这样的组合?我不是专注于南方的人,但似乎是在Django中进行模式迁移的方式。

2 个答案:

答案 0 :(得分:0)

我认为两个应用程序使用自定义字段,South抱怨这个。在这里,您可以阅读有关如何为这些自定义字段启用南方的信息:http://south.aeracode.org/docs/customfields.html

两个相关链接:

答案 1 :(得分:0)

因为我们确实知道语言的数量永远不会改变,所以我们改用了每种语言的字段和一个简单的机制来自动读取当前语言的正确字段。我们的实现使用如下:

class Question(models.Model):
    __metaclass__ = LocalizeModelBase

    text_de = models.TextField(verbose_name=_(u"question text (german)"))
    text_en = models.TextField(verbose_name=_(u"question text (english)"))
    text = Translate

Question().text然后根据当前语言自动返回正确的字段,并回退到默认语言。

它背后的实现应该是非常自我解释的:

from django.db.models.base import ModelBase
from django.utils.translation import get_language
from django.conf import settings

__all__ = ('Translate', 'LocalizeModelBase')

# a dummy placeholder object
Translate = object()


class LocalizeModelBase(ModelBase):
    """This meta-class provides automatically translated content properties. Set
    a model field to `Translate` and it will automatically return the property
    with the name of the current language. E.g. if there is a normal member
    `text_de`, a member `text = Translate` and the current language is `de`, then
    an object will return the content of `text_de` when it is asked for the value
    of `text`.
    """
    def __new__(metacls, classname, bases, classDict):
        # find all classDict entries that point to `Translate`
        for key in classDict.keys():
            if classDict[key] is Translate:
                # replace them with a getter that uses the current language
                classDict[key] = make_property(key)
        return super(LocalizeModelBase, metacls).__new__(metacls, classname, bases, classDict)


def make_property(k):
    """Creates a new property that implements the automatic translation
    described above. Every use of `Translate` in a class definition will be
    replaces with a property returned by this function."""
    def pget(self):
        try:
            # try to return the attribute for the current language
            return getattr(self, "%s_%s" % (k, get_language()))
        except AttributeError:
            # use the default language if the current language is not available
            return getattr(self, "%s_%s" % (k, settings.LANGUAGE_CODE))
    return property(pget)