我认为这是可能的,而且这是最快的方法之一(即使是测试是否有效),就是通过猴子补丁 Django 翻译模块来添加回退语言支持,像这样(未经测试):
from django.utils.translation import trans_real
...
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
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:
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
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)
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)
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
模块的源代码作为基础,创建自定义翻译函数,仅在应用程序中的少数位置使用。