class ArticleForm(ModelForm):
title = forms.CharField( error_messages={'required': 'Please enter title'},
max_length=128 ,
required=True,
widget=forms.TextInput(attrs={'size':60}))
contents = forms.CharField( required=True,
widget=forms.Textarea(attrs={'cols': 160, 'rows': 20}))
email = forms.CharField(max_length=128, widget=forms.TextInput(attrs={'size':60}))
writed_by = forms.CharField(max_length=100,
required=True,
widget=forms.TextInput(attrs={'size':60}))
class Meta:
model = Article
fields = ["title", "writed_by", "email", "contents"]
我想在没有输入标题时显示“请输入标题”消息。但表单显示默认消息。
此代码中的问题是什么?
感谢。
答案 0 :(得分:2)
您可以尝试在__init__()
中设置自定义消息,如下所示:
class ArticleForm(ModelForm):
title = forms.CharField(max_length=128,
required=True,
widget=forms.TextInput(attrs={'size': 60}))
class Meta:
model = Article
fields = ["title"]
def __init__(self, *args, **kwargs):
super(ArticleForm, self).__init__(*args, **kwargs)
# add custom error messages
self.fields['title'].error_messages['required'] = 'Please enter title'