我在Django中编写了这个函数来覆盖'标签后缀和表单字段错误消息。在同一个函数中,lebel后缀正在工作(冒号被删除)但错误消息没有被自定义的替换。 这是带有函数的表单类:
class User_accountModelForm(forms.ModelForm):
# to remove colons from the labels:
def __init__(self, *args, **kwargs):
kwargs.setdefault('label_suffix', '')
super(User_accountModelForm, self).__init__(*args, **kwargs)
# changing error messages:
for field in self.fields.values():
field.error_messages = {'required':'The field {fieldname} is required'.format(fieldname=field.label)}
class Meta:
model = User_account
fields = ['first_name', 'other fields']
感谢任何帮助或线索
答案 0 :(得分:1)
要覆盖表单错误消息,请将其添加到表单Meta
;另见ModelForm
docs:
class User_accountModelForm(ModelForm):
class Meta:
model = User_account
fields = ['first_name', 'other fields']
error_messages = {
'first_name': {
# for example:
'max_length': _("This writer's name is too long."),
},
}