Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

python - Django - change field validation message

I have an email field in my Newsletter form that looks like this:

class NewsletterForm(forms.ModelForm):

    email = forms.EmailField(widget=forms.EmailInput(attrs={
        'autocomplete': 'off',
        'class': 'form-control',
        'placeholder': _('seuemail@email.com'),
        'required': 'required'
    }))

    class Meta:
        model = Newsletter
        fields = ['email', ]

My form is working, but when I type "ahasudah@ahs" without a DOT for the domain name, I get this error "Enter a valid email address"

Where is this?

I just checked the original source and I couldn't find an error message to override like other fields.

https://github.com/django/django/blob/master/django/forms/fields.py#L523

Any ideas how to override this message?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In fact you can do this in two different ways in two different level:

  1. You can do this at the level of the form validation:
class NewsletterForm(forms.ModelForm):

    email = forms.EmailField(
      widget=forms.EmailInput(attrs={
        'autocomplete': 'off',
        'class': 'form-control',
        'placeholder': _('seuemail@email.com'),
        'required': 'required'
      }),
      error_messages={'invalid': 'your custom error message'}
    )

    class Meta:
        model = Newsletter
        fields = ['email', ]
  1. the second way at the level of the model:

2.1. you can do the same as in the form:

    email = models.EmailField(error_messages={'invalid':"you custom error message"})

2.2. or you use django built-in Validators:

   from django.core.validators import EmailValidator

   email = models.EmailField(validators=[EmailValidator(message="your custom message")]) # in you model class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...