我认为这是可能的,并且最快的方法之一(即使测试它是否有效)是猴子补丁 Django 翻译模块以添加这样的后备语言支持(未测试):
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
以上两个函数取自django.utils.translation.trans_real
模块。只是在这些函数中添加了几行。您还需要修改其他函数(例如gettext
、ngettext
、pgettext
)以接受fallback_language
参数并将其传递给上述两个函数。请尝试此代码是否有效。
请注意,monkey-patching 是项目范围的 - 它也会影响您的整个应用程序和第三方应用程序。或者,您可以将django.utils.translation.trans_real
模块的源代码作为基础来创建仅在应用程序中的少数地方使用的自定义翻译功能。