标准翻译

 来引入这个函数以节省键入时间.
 被标记为待翻译字符串:
 
from django.utils.translation import ugettext as _
def my_view(request):
  output = _("Welcome to my site.")
  return HttpResponse(output)

显然,你也可以不使用别名来编码。 下面这个例子和前面两个例子相同:

1
from django.utils.translation import ugettext
def my_view(request):
  output = ugettext("Welcome to my site.")
  return HttpResponse(output)

翻译字符串对于计算出来的值同样有效。 下面这个例子等同前面一种:

def my_view(request):
  words = ['Welcome', 'to', 'my', 'site.']
  output = _(' '.join(words))
  return HttpResponse(output)

翻译对变量也同样有效。 这里是一个同样的例子:

def my_view(request):
  sentence = 'Welcome to my site.'
  output = _(sentence)
  return HttpResponse(output)

(以上两个例子中,对于使用变量或计算值,需要注意的一点是Django的待翻译字符串检测工具,make-messages.py ,将不能找到这些字符串。 稍后,在 makemessages 中会有更多讨论。)

1
 的字符串可以接受占位符,由Python标准命名字符串插入句法指定的。 例如:
 
 def my_view(request, m, d):
  output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
  return HttpResponse(output)

这项技术使得特定语言的译文可以对这段文本进行重新排序。 比如,一段英语译文可能是"Today is November 26." ,而一段西班牙语译文会是 "Hoy es 26 de Noviembre." 使用占位符(月份和日期)交换它们的位置。

 )。 如果你使用位置插入的话,翻译动作将不能重新排序占位符文本。
 

标记字符串为不操作

 函数来标记一个不需要立即翻译的字符串。 这个串会稍后从变量翻译。
 
使用这种方法的环境是,有字符串必须以原始语言的形式存储(如储存在数据库中的字符串)而在最后需要被翻译出来(如显示给用户时)。
 

惰性翻译

 被调用时翻译。
3
help_text,按以下进行:
 
 from django.utils.translation import ugettext_lazy
class MyThing(models.Model):
  name = models.CharField(help_text=ugettext_lazy('This is the help text'))

在这个例子中, ugettext_lazy() 将字符串作为惰性参照存储,而不是实际翻译。 翻译工作将在字符串在字符串上下文中被用到时进行,比如在Django管理页面提交模板时。

ugettext_lazy()对象并不知道如何把它自己转换成一个字节串。如果你尝试在一个需要字节串的地方使用它,事情将不会如你期待的那样。 同样,你也不能在一个字节串中使用一个 unicode 字符串。所以,这同常规的Python行为是一致的。 例如:
1
 
# 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()的结果。 在您的代码中,那是一个漏洞。

 (下划线)作为别名,就像这样:
1
 
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_naneverbose_name_plural选项,而不是依赖于Django默认的verbose_nameverbose_name_plural(通过检查model的类名得到)。

1
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')