使用模型表单创建自定义错误消息 [英] Create Custom Error Messages with Model Forms
本文介绍了使用模型表单创建自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以看到使用表单时如何向字段添加错误消息,但是模型表单呢?
I can see how to add an error message to a field when using forms, but what about model form?
这是我的测试模型:
class Author(models.Model):
first_name = models.CharField(max_length=125)
last_name = models.CharField(max_length=125)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
我的模型表格:
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
字段上的错误消息:名字
和姓氏
是:
The error message on the fields: first_name
and last_name
is:
此字段为必填字段
This field is required
如何更改模型形式?
推荐答案
对于简单的情况,您可以指定自定义错误消息
For simple cases, you can specify custom error messages
class AuthorForm(forms.ModelForm):
first_name = forms.CharField(error_messages={'required': 'Please let us know what to call you!'})
class Meta:
model = Author
这篇关于使用模型表单创建自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文