开发者

Django - How to add custom error message in Form?

开发者 https://www.devze.com 2023-03-31 08:24 出处:网络
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 be

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    
0

精彩评论

暂无评论...
验证码 换一张
取 消