Django:在不使用语言会话/ cookie的情况下翻译字符串

时间:2009-10-13 08:01:08

标签: django internationalization

在django中是否有办法将字符串翻译成另一种语言而不是语言会话或cookie中指定的语言?

我的意思是在调用ugettext时这样做。像这样的东西,'en'是语言代码:

from django.utils.translation import ugettext as _

def translate():
   translated_string =  _('Translate me', 'en')

1 个答案:

答案 0 :(得分:5)

通过django/middleware/locale.py查看,您似乎可以致电:

from django.utils import translation
translation.activate(language)

以下是整个LocaleMiddleware课程,供您进行修改:

def process_request(self, request):
    language = translation.get_language_from_request(request)
    translation.activate(language)
    request.LANGUAGE_CODE = translation.get_language()

def process_response(self, request, response):
    patch_vary_headers(response, ('Accept-Language',))
    if 'Content-Language' not in response:
        response['Content-Language'] = translation.get_language()
    translation.deactivate()
    return response