Django - How to add custom error message in Form?
How can I add a custom error message in a Django form?
For example, I want to add a new error 开发者_如何学Gomessage in a view if two e-mails aren't the same.
First you must define a function that begins with clean_[your field name] --- for example: def clean_email. Then write your validation in your function and assign an error name and use it in error_messages of your field.
class ValidationForm(forms.Form):
email = forms.EmailField(label = 'Email', error_messages = {'invalid': 'Your Email Confirmation Not Equal With Your Email'})
email_confirmation = forms.EmailField(label = 'Email Confirmation')
def clean_email(self):
if email != email_confirmation:
raise ValidationError(self.fields['email'].error_messages['invalid'])
return email
精彩评论