Django:如何检测翻译是否已激活?

2 投票
3 回答
784 浏览
提问于 2025-04-15 15:16

django.utils.translation.get_language() 这个函数会返回默认的语言设置,如果翻译功能没有被开启。那么,有没有办法检查一下翻译功能是否已经被开启(通过 translation.activate())呢?

3 个回答

-2

遇到这种问题时,最好先看看源代码,这样比在网上发帖要快得多!

Django在后台做了一些神奇的事情,它使用了一种调度器来模拟禁用翻译的效果。

你可以采取的最佳方法是:

import setttings
assert settings.USE_i18N == True
0

这要看你的应用和架构了……

Ignacio 提供的解决方案应该是可行的,但如果你在一个还没有激活的线程里运行呢?

我会用 Ignacio 的方法,再加一个所有线程都能看到的队列,修改 trans_real.activate 函数,并在队列里设置属性。

3

这段代码可能有点黑科技,但在1.1.1版本中应该能用:

import django.utils.translation.trans_real as trans
from django.utils.thread_support import currentThread

def isactive():
  return currentThread() in trans._active

撰写回答