Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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': _('[email protected]'),
        '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?

like image 591
Lara Avatar asked Dec 24 '15 00:12

Lara


People also ask

How do I increase validation error in Django?

To create such an error, you can raise a ValidationError from the clean() method. For example: from django import forms from django. core.

What is form AS_P in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.

How do you remove this field is required Django?

If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file.


1 Answers

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': _('[email protected]'),
        '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
like image 104
Dhia Avatar answered Sep 17 '22 13:09

Dhia