我的表单中的必填字段错误显示在输入字段值属性中:
Django forms.py
class ProfileForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
pic = forms.ImageField(required=False, error_messages = {'invalid':_("Image files only")}, widget=forms.FileInput)
#http://stackoverflow.com/questions/3436712/custom-error-messages-with-model-form
class Meta:
model = Profile
fields = ('pic', 'mobile', 'bio', 'location', 'website')
widgets = {
"mobile" : TextInput(attrs={"class" : "mobile"}),
"bio" : Textarea(attrs={"class" : "bio", 'cols': 50, 'rows': 5}),
}
error_messages = {
'mobile': {
'required': _("Please enter your mobile number."),
},
'bio': {
'required': _("Please enter your bio."),
},
'location': {
'required': _("Please enter location."),
},
'website': {
'required': _("Please enter your website."),
},
}
help_texts = {
'mobile': _('Fill your active mobile numbers.'),
}
labels = {
"pic": _("Photo"),
"mobile": _("Mobile"),
"bio": _("bio"),
}
def is_valid(self):
form = super(ProfileForm, self).is_valid()
for f, error in self.errors.iteritems():
if f != '__all__':
self.fields[f].widget.attrs.update({'class': 'error', 'value': removetags(error, 'ul li')})
return form
Django Template
:
<h2>Edit Profile</h2>
<form action="/edit" method="post" enctype="multipart/form-data" >{% csrf_token %}
<p class='profile_p'>{{ profile_form.pic.label_tag }}
<span class='pic_upload_btn'>Upload Profile Picture</span>
{{ profile_form.html_name }}
{% if pic %}
<img src='{{STATIC_URL}}images/{{ pic.pic }}' width='100' height='100' />
{% endif %}
{{ profile_form.pic }}
</p>
<p>{{ profile_form.mobile.label_tag }}
{{ profile_form.mobile }}
{{ profile_form.mobile.help_text }}
<span>{{ profile_form.mobile.errors }}</span>
</p>
<p>{{ profile_form.bio.label_tag }}
{{ profile_form.bio }}
</p>
<p>{{ profile_form.location.label_tag }}
{{ profile_form.location }}
{{ profile_form.location.errors }}
</p>
<p>{{ profile_form.website.label_tag }}
{{ profile_form.website }}
{{ profile_form.website.errors }}
</p>
<input type="submit" id="btnSignUp" value="Update">
</form>
HTML
如果移动字段保持为空并且提交了表单。它在输入字段内显示红色的错误消息:
<input id="id_mobile" class="error" type="text" value="Please enter your mobile number." name="mobile">
如何防止错误,使它们不出现在输入字段中?
答案 0 :(得分:1)
解决了自己。
通过在forms.py中注释以下代码来修复上述错误:
def is_valid(self):
form = super(ProfileForm, self).is_valid()
for f, error in self.errors.iteritems():
if f != '__all__':
self.fields[f].widget.attrs.update({'class': 'error', 'value': removetags(error, 'ul li')})
return form
谢谢大家的帮助。