在运行时如何在Django中回归多种语言? [英] How to fall back to multiple languages in Django at runtime?

查看:142
本文介绍了在运行时如何在Django中回归多种语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个使用Django翻译功能的Django应用程序,可以为多种语言提供本地化。但是,我还使用Django的翻译功能,根据当前登录的用户设置,将某些术语转换为不同的行业



例如,对于在学习评估行业工作的英语用户,我想要以下行为:



对于给定页面的请求:


  1. 查找用户的自然语言(例如德语)

  2. 查找用户的行业(例如学习评估)

  3. 激活德语/学习评估语言(例如,translation.activate(learning-assessment-de)

学习评估-de.po文件将仅翻译项目中所有字符串的一部分,因为只能在某些行业特定术语中进行翻译。



这是一个问题:



当一个字符串丢失时,我希望Django回到德语(在上面的步骤1中确定),而不是英语(我的settings.py中的默认语言)。



我的默认英语/德语.po文件将承担某个行业



这是可能吗?

解决方案

我认为这是可能的最简单的方法之一(即使测试是否可行)将是为了修改Django翻译模块来添加这样的后备语言支持(未测试):



导入其他东西


#添加了`fallback_language`参数$

  from django.utils.translation import trans_real 
...# b $ b def do_translate(message,translation_function,fallback_language = None):

使用给定的'translation_function'名称翻译'消息' -
将是gettext或ugettext 。它使用当前线程来查找要使用的
翻译对象。如果没有激活当前的翻译,
消息将通过默认的翻译对象运行。

全局_default

#str()允许通过测试的消息在Python 2上保持测试
eol_message = message.replace(str(' \\(\\'),str('\\\
'))替换(str('\r'),str('\\\
'))
t = getattr(_active,value ,无)
如果t不是无:
result = getattr(t,translation_function)(eol_message)
其他:

#使用其他语言作为回退
如果fallback_language不是无:
fallback = translate(fallback_language)
result = getattr(_default,translation_function)(eol_message)

else:
如果_default是无的:
从django.conf导入设置
_default =翻译(settings.LANGUAGE_CODE)
result = getattr(_default,translation_function)(eol_message)
如果isinstance(消息,SafeData ):
return mark_safe(result)
返回结果

#添加`fallback_language`参数
def do_ntranslate(singular,plural,number,translation_function,fallback_language = None):
全局_default

t = getattr(_active,value,None)
如果t不是None:
return getattr(t,translation_function)(单数,复数,数)

#使用其他语言作为备用。
如果fallback_language不是None:
fallback = translation(fallback_language)
return getattr(fallback,translation_function)(单数,复数,数)

如果_default为无:
from django.conf import settings
_default = translation(settings.LANGUAGE_CODE)
return getattr(_default,translation_function)(单数,复数,数)


#用自定义覆盖Django函数。
trans_real.do_translate = do_translate
trans_real.do_ntranslate = do_ntranslate

上面两个函数取自 django.utils.translation.trans_real 模块。只是添加了几行这些功能。您还需要修改其他函数(例如 gettext ngettext pgettext )来接受 fallback_language 参数并将其传递给上述两个参数。请尝试此代码的工作原理。



请注意,该猴子修补程序是项目范围的,它也影响到您的整个应用程序和第三方应用程序。或者您可以将 django.utils.translation.trans_real 模块的来源作为基础,创建仅在应用程序中的少数位置使用的自定义翻译功能。 / p>

I am building a Django app that uses Django's translation features to provide localization to multiple languages. But I am also using Django's translation features to translate certain terminology into different industries based on the currently logged in user's settings.

For example, for an English speaking user working in the learning assessment industry, I want the following behavior:

For a given request to a page:

  1. Look up the user's natural language (e.g., German)
  2. Look up the user's industry (e.g., learning assessment)
  3. Activate the German/Learning Assessment language (e.g., translation.activate("learning-assessment-de")

The "learning-assessment-de" .po file will only translate a subset of all the strings in the project, because it's only there to translate certain industry-specific terminology.

This is the question:

When a string is missing, I want Django to fall back to German (determined in step #1 above) rather than English (the default language in my settings.py).

My default English/German .po files will assume a certain industry.

Is this possible?

解决方案

I think it's possible and one of the fastest ways to do this (even if to test if it works) would be to monkey-patch Django translation module to add fallback language support like this (not tested):

from django.utils.translation import trans_real
... # Import other things


# Added `fallback_language` parameter
def do_translate(message, translation_function, fallback_language=None):
    """
    Translates 'message' using the given 'translation_function' name -- which
    will be either gettext or ugettext. It uses the current thread to find the
    translation object to use. If no current translation is activated, the
    message will be run through the default translation object.
    """
    global _default

    # str() is allowing a bytestring message to remain bytestring on Python 2
    eol_message = message.replace(str('\r\n'), str('\n')).replace(str('\r'), str('\n'))
    t = getattr(_active, "value", None)
    if t is not None:
        result = getattr(t, translation_function)(eol_message)
    else:

        # Use other language as fallback.
        if fallback_language is not None:
            fallback = translation(fallback_language)
            result = getattr(_default, translation_function)(eol_message)

        else:
            if _default is None:
                from django.conf import settings
                _default = translation(settings.LANGUAGE_CODE)
            result = getattr(_default, translation_function)(eol_message)
    if isinstance(message, SafeData):
        return mark_safe(result)
    return result

# Added `fallback_language` parameter
def do_ntranslate(singular, plural, number, translation_function, fallback_language=None):
    global _default

    t = getattr(_active, "value", None)
    if t is not None:
        return getattr(t, translation_function)(singular, plural, number)

    # Use other language as fallback.
    if fallback_language is not None:
       fallback = translation(fallback_language)
       return getattr(fallback, translation_function)(singular, plural, number)

    if _default is None:
        from django.conf import settings
        _default = translation(settings.LANGUAGE_CODE)
    return getattr(_default, translation_function)(singular, plural, number)


# Override Django functions with custom ones.
trans_real.do_translate = do_translate
trans_real.do_ntranslate = do_ntranslate

The two above functions are taken from the django.utils.translation.trans_real module. Just added few lines to these functions. You will also need to modify the other functions (e.g. gettext, ngettext, pgettext) to accept the fallback_language parameter and pass it to the two above ones. Please try if this code works.

Note, that monkey-patching is project-wide - it affects Your whole application and third-party applications too. Alternatively You may take the source of the django.utils.translation.trans_real module as a base to create custom translation functions that will be used only in few places in your application.

这篇关于在运行时如何在Django中回归多种语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆