Django override default form error messages
Also come here from google and what I need is to overwrite the default required messages for all fields in my form rather than passing the error_messages argument everytime I defined new form fields. Also, I'm not ready yet to delve into i18n, this apps not required to be multilingual. The comment in this blog post is the closest to what I want:-
http://davedash.com/2008/11/28/custom-error-messages-for-django-forms/
For all form fields that has required messages, this is what I did:-
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
for k, field in self.fields.items():
if 'required' in field.error_messages:
field.error_messages['required'] = 'You have to field this.'
class MUserForm(MyForm):
user = forms.CharField(
label="Username",
)
....
The easiest way is to provide your set of default errors to the form field definition. Form fields can take a named argument for it. For example:
my_default_errors = {
'required': 'This field is required',
'invalid': 'Enter a valid value'
}
class MyForm(forms.Form):
some_field = forms.CharField(error_messages=my_default_errors)
....
Hope this helps.
To globally override the "required" error message, set the default_error_messages class attribute on Field:
# form error message override
from django.forms import Field
from django.utils.translation import ugettext_lazy
Field.default_error_messages = {
'required': ugettext_lazy("This field is mandatory."),
}
This needs to happen before any fields are instantiated, e.g. by including it in settings.py.