views:

459

answers:

4

Hi all, How can I overwrite the default form error messages (for example: need them in other language) for the all apps in my project (or at least for 1 app)

Thanks!

+2  A: 

You may want to look at Django's excellent i18n support.

cpharmston
A: 

Hmm, seems there is no easy workaround for the problem.

Wile skimming through the django code, I've found that default error messages are hard-coded into each form field class, for ex:

class CharField(Field):
default_error_messages = {
    'max_length': _(u'Ensure this value has at most %(max)d characters (it has %(length)d).'),
    'min_length': _(u'Ensure this value has at least %(min)d characters (it has %(length)d).'),
}

And the easiest way is to use the error_messages argument, so I had to write the wrapper function:

def DZForm(name, args = {}):
error_messages = {
    'required': u'required',
    'invalid': u'invalid',
}
if 'error_messages' in args.keys():
    args['error_messages'] = error_messages.update(args['error_messages'])
else:
    args['error_messages'] = error_messages
return getattr(forms, name)(**args)

If smdb knows more elegent way of doing this would really appreaciate to see it :)

Thanks!

Brock
+2  A: 

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.

Juergen Brendel
Yep. But I want to override default with having the flexibility to set form specific...In your case I'll have to merge default and form error message dicts manually each time
Brock
A: 

Since this page comes up in a search, perhaps it's worth adding my $0.02 even though the question is old. (I'm still getting used to Stack Overflow's particular etiquette.)

The underscore ("_") is an alias (if that's the right term) for ugettext_lazy; just look at the import statements at the top of the file with "hard-coded" messages. Then, Django's internationalization docs should help, e.g. http://www.djangobook.com/en/2.0/chapter19/

Scott Lawton