The required field error in my form are shown in input field value attribute:
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
If mobile field is kept empty and form is submitted. It displays error message inside input field with red color:
<input id="id_mobile" class="error" type="text" value="Please enter your mobile number." name="mobile">
How can I prevent the errors so they do not appear in input field?