使用 django.utils.translation.gettext_lazy() 函數,使得其中的值只有在訪問時才會被翻譯,而不是在 gettext_lazy() 被調用時翻譯。
例如:要翻譯一個模型的 help_text,按以下進行:
from django.utils.translation import ugettext_lazyclass MyThing(models.Model): name = models.CharField(help_text=ugettext_lazy('This is the help text'))在這個例子中, ugettext_lazy() 將字符串作為惰性參照存儲,而不是實際翻譯。 翻譯工作將在字符串在字符串上下文中被用到時進行,比如在Django管理頁面提交模板時。
在Python中,無論何處你要使用一個unicode 字符串(一個unicode 類型的對象),您都可以使用一個 ugettext_lazy() 調用的結果。 一個ugettext_lazy()對象并不知道如何把它自己轉換成一個字節串。如果你嘗試在一個需要字節串的地方使用它,事情將不會如你期待的那樣。 同樣,你也不能在一個字節串中使用一個 unicode 字符串。所以,這同常規的Python行為是一致的。 例如:
# This is fine: putting a unicode proxy into a unicode string.u"Hello %s" % ugettext_lazy("people")# This will not work, since you cannot insert a unicode object# into a bytestring (nor can you insert our unicode proxy there)"Hello %s" % ugettext_lazy("people")如果你曾經見到到像"hello"這樣的輸出,你就可能在一個字節串中插入了ugettext_lazy()的結果。 在您的代碼中,那是一個漏洞。
如果覺得 gettext_lazy 太過冗長,可以用 _ (下劃線)作為別名,就像這樣:
from django.utils.translation import ugettext_lazy as _class MyThing(models.Model): name = models.CharField(help_text=_('This is the help text'))在Django模型中總是無一例外的使用惰性翻譯。 為了翻譯,字段名和表名應該被標記。(否則的話,在管理界面中它們將不會被翻譯) 這意味著在Meta類中顯式地編寫verbose_nane和verbose_name_plural選項,而不是依賴于Django默認的verbose_name和verbose_name_plural(通過檢查model的類名得到)。
from django.utils.translation import ugettext_lazy as _class MyThing(models.Model): name = models.CharField(_('name'), help_text=_('This is the help text')) class Meta: verbose_name = _('my thing') verbose_name_plural = _('mythings')新聞熱點
疑難解答
圖片精選