【问题标题】:How to translate labels and validation messages of forms within Django如何在 Django 中翻译表单的标签和验证消息
【发布时间】:2013-01-26 20:11:22
【问题描述】:

每当我跑步时:

$ ./manage.py makemessages -a -l es -e .py

它只包括用于翻译,在 locale/es/LC_MESSAGES/django.po 中我在 MY 应用程序中标记的字符串,但我想翻译标记为可翻译的 django 形式的字符串,例如:https://github.com/django/django/blob/master/django/contrib/auth/forms.py#L64-L84

有什么方法可以让makemessages 翻译 Django 中 Forms 的标签和验证错误消息,而不必覆盖这些表单?

提前感谢您的帮助! :)

【问题讨论】:

  • 已经翻译好了。 Django 附带了所有内置表单和模板的 70 多种翻译。

标签: python django django-forms translation


【解决方案1】:

这些字符串的翻译已经由 django 项目完成:https://github.com/django/django/blob/master/django/contrib/auth/locale/es_MX/LC_MESSAGES/django.po#L42

您无需自己进行翻译。

您应该已经在您的应用中翻译了它们。

【讨论】:

    【解决方案2】:

    如上所述,翻译是 Django 自带的。但是,如果您想要的语言翻译不完整或不符合您的意愿,您始终可以复制字符串以翻译到您的项目,您的翻译将优先于 Django 附带的翻译。

    要实现这一点,只需创建文件并包含这些要翻译的字符串。例如app/i18n.py:

    '''
    Fake file to translate messages from django.contrib.auth.
    '''
    
    def _(text):
        return text
    
    def fake():
        _(u'This username is already taken. Please choose another.')
    

    现在makemessages 将获取这些字符串,您将能够翻译它们。

    【讨论】:

      【解决方案3】:

      如果您使用的是 ModelForm,请查看 this answer 以了解自定义标签和错误消息:

      class AuthorForm(ModelForm):
          class Meta:
              model = Author
              fields = ('name', 'title', 'birth_date')
              labels = {
                  'name': _('Writer'),
              }
              help_texts = {
                  'name': _('Some useful help text.'),
              }
              error_messages = {
                  'name': {
                      'max_length': _("This writer's name is too long."),
                  },
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-22
        • 1970-01-01
        • 2016-01-09
        • 1970-01-01
        • 2017-12-03
        • 1970-01-01
        相关资源
        最近更新 更多