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!
事实证明,这是一个非常难以查找的主题,我希望能为其他人节省时间。更简单的方法是什么?
最佳答案
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 - 覆盖 Django 1.6 中的 ModelForm 字段错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21740742/