【问题标题】:Overriding ModelForm field error messages in Django 1.6在 Django 1.6 中覆盖 ModelForm 字段错误消息
【发布时间】:2014-03-11 12:49:52
【问题描述】:

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 有一种更简单的方法来覆盖字段错误消息。一世 还没有时间实现它,但你应该随意看看 赶紧用起来吧!

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

【问题讨论】:

  • 好吧,我问这个也是希望sharing the answer I'd finally found,但我想我必须等8个小时才能这样做。 SO 真的是一个非常令人生畏的社区,尝试进入......
  • 这看起来像是 stackoverflow.com/a/3437158/1637351 的副本。
  • 它很相似,但我专门试图在 Django 1.6 中找到新方法,该问题或答案中均未提及。也许答案可能是更好的选择,但至少现在谷歌搜索“django 1.6 overriding modelform error messages”实际上是有帮助的(因为它链接在这里)。

标签: django django-forms


【解决方案1】:

来自Django 1.6 release notes

ModelForm 接受几个新的 Meta 选项。

  • localized_fields 列表中包含的字段将被本地化(通过在表单字段上设置 localize)。
  • 标签、help_texts 和 error_messages 选项可用于自定义默认字段,详情请参阅 Overriding the default fields

由此而来:

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?

【讨论】:

    猜你喜欢
    • 2018-02-01
    • 1970-01-01
    • 2011-02-25
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 2011-04-28
    • 1970-01-01
    相关资源
    最近更新 更多