我想更改默认错误消息,当重复条目尝试保存时它们应该是唯一的,即 unique=True
。很像这样:
email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."})
但是,在上面的例子中,unique
是一个猜测,并且不起作用。我也无法找出错误的实际名称。有谁知道正确的名字吗?
请注意,此验证是模型级别的,而不是表单验证。
编辑:
更多信息,目前当前错误消息由 form.errors
显示:
[model_name] with this [field_label] already exists
这对用户来说不是很友好,所以我想覆盖它...
最佳答案
非常感谢。
email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."})
现在效果很好。
如果你想自定义像invalided
这样的error_messages,在forms.ModelForm
中做吧
email = forms.EmailField(error_messages={'invalid': 'Your email address is incorrect'})
但是 unique
消息应该在 model
字段中自定义,正如 ben 提到的
email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."})
关于为唯一字段显示的 Django 错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5514621/