Django - change field change 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 works, but when I type "ahasudah @ahs" without a DOT for the domain name, I get this error "Enter a valid email address"

Where is it?

I just checked the source source and I could not find the error message to override, like other fields.

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

Any ideas on how to override this post?

+6
source share
1 answer

In fact, you can do this in two different ways at two different levels:

  • You can do this at the form validation level:
 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 method at the model level:

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 
+3
source

All Articles