Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django override default form error messages

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!

like image 997
Brock Avatar asked Sep 26 '09 18:09

Brock


3 Answers

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.

like image 161
Juergen Brendel Avatar answered Nov 08 '22 01:11

Juergen Brendel


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.

like image 45
til Avatar answered Nov 08 '22 03:11

til


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",
    )
    ....
like image 7
k4ml Avatar answered Nov 08 '22 03:11

k4ml