django - 覆盖 Django 1.6 中的 ModelForm 字段错误消息

标签 django django-forms

hjwp的精彩Test-Driven Development with Python book演示重写 chapter 11 中的默认 ModelForm 字段错误消息:

from django import forms

from lists.models import Item

class ItemForm(forms.models.ModelForm):

    class Meta:
        [...]


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        empty_error = "You can't have an empty list item"
        self.fields['text'].error_messages['required'] = empty_error

但随后宣称(这是一项正在进行的工作)...

Django 1.6 has a simpler way of overriding field error messages. I haven’t had time to implement it yet, but you should feel free to look it up and use it!

事实证明,这是一个非常难以查找的主题,我希望能为其他人节省时间。更简单的方法是什么?

最佳答案

来自Django 1.6 release notes :

ModelForm accepts several new Meta options.

  • Fields included in the localized_fields list will be localized (by setting localize on the form field).
  • The labels, help_texts and error_messages options may be used to customize the default fields, see Overriding the default fields for details.

从那开始:

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."),
            },
        }

相关:Django's ModelForm - where is the list of Meta options?

关于django - 覆盖 Django 1.6 中的 ModelForm 字段错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21740742/

相关文章:

django - 如何实现 OneToOne 关系的嵌套 URL?

Django:如何在呈现之前但在表单初始化之后修改表单字段的值?

python - Django_Hosts 导入错误

python - 更改 django-haystack 中的默认 View

django - Django UpdateView 中的 {{ form.object }}

python - 动态添加字段的 django 表单集可以具有持久数据吗?

python - Django 表单 : reference fields from foreign key

python - 如何在 Ubuntu 14.04 中通过 Apache 网络服务器运行两个 django 项目?

Django clean 方法在 POST 上抛出 KeyError

django modelForm,只需要保存选定的字段