简体   繁体   English

Django在模型保存上转换数据

[英]Django translate data on model save

I need to translate the data automatically in the django admin. 我需要在django管理员中自动转换数据。

I'm currently translating all the static text manually using django rosetta, to simplify the translation. 我目前正在使用django rosetta手动翻译所有静态文本,以简化翻译。 What I need to do is translate all the data automatically using Microsoft translator API in the admin interface. 我需要做的是在管理界面中使用Microsoft Translator API自动翻译所有数据。

Lets assume I have a function that do the translation. 假设我有一个执行翻译的函数。 Should I use django-modeltranslation with the translation function and override the save function for each model? 我应该将django-modeltranslation与翻译功能一起使用,并覆盖每个模型的保存功能吗?

Any tips, modules, or code snippets that can help. 可以提供帮助的任何提示,模块或代码段。

If the language you need to translate to and translate from is fixed, as in you don't intend the user to input data in several languages, then you could translate the data in your model save method: 如果您需要翻译的语言是固定的,因为您不希望用户以多种语言输入数据,那么您可以使用模型保存方法来翻译数据:

class ModelName(models.Model):

    data = models.CharField()

    def save(self):
        """ Extension of parent save method """

        for name in ModelName._meta.get_all_field_names():
            field = getattr(name, ModelName, None)
            field = translate(field)

        super(ModelName, self).save()

Another option would be to do the translation in the input validation of the data, if it is a form: 另一个选择是在数据的输入验证中进行转换,如果它是以下形式:

class ModelNameForm(forms.Form):

    data = forms.CharField()

    def clean_data(self):
        data = self.cleaned_data['data']
        return translate(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM