Django - change field validation message

南楼画角 提交于 2019-12-30 18:05:44

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/34445801/django-change-field-validation-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!