我可以看到使用表单时如何向字段添加错误消息,但是模型表单呢?
这是我的测试模型:
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
在字段中的错误信息:first_name和last_name是:
first_name
last_name
这是必填栏
如何以模型形式进行更改?
对于简单的情况,你可以指定自定义错误消息
class AuthorForm(forms.ModelForm): first_name = forms.CharField(error_messages={'required': 'Please let us know what to call you!'}) class Meta: model = Author
Django 1.6的新功能:
ModelForm接受几个新的Meta选项。
localized_fields
help_texts
error_messages
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."), }, }