Django override default form error messages

前端 未结 10 1618
情歌与酒
情歌与酒 2020-12-04 10:03

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!

相关标签:
10条回答
  • 2020-12-04 10:14

    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!

    0 讨论(0)
  • 2020-12-04 10:16

    Say I have a BaseForm with some error_messages dictionary like:

    error_messages = {
        'required': 'This field is required',
        'caps': 'This field if case sensitive' 
    }
    

    and I want to override one of the error messages:

    class MySpecialForm(BaseForm):
        def __init__(self, *args, **kwargs):
            super(MySpecialForm, self).__init__(*args, **kwargs)
            self.error_messages['caps'] = 'Hey, that CAPSLOCK is on!!!'
    

    Basically, just override one of the dictionary values. I am not sure how it would work with internationalization though.

    0 讨论(0)
  • 2020-12-04 10:17

    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",
        )
        ....
    
    0 讨论(0)
  • 2020-12-04 10:17

    from ProDjango book:

    from django.forms import fields, util
    
    
    class LatitudeField(fields.DecimalField):  
        default_error_messages = {
            'out_of_range': u'Value must be within -90 and 90.',
        }
    
    
        def clean(self, value):  
            value = super(LatitudeField, self).clean(value)  
            if not -90 <= value <= 90:  
                raise util.ValidationError(self.error_messages['out_of_range'])
            return value
    
    0 讨论(0)
  • 2020-12-04 10:17
    This is worked for me
    class SignUpForm(forms.ModelForm):
        username = forms.CharField(required=True, max_length=50)
        username.error_messages['required'] = _('Username field is required')
    
        first_name = forms.CharField(required=True, max_length=50)
        first_name.error_messages['required'] = _('First name field is required')
    
        last_name = forms.CharField(required=True, max_length=50)
        last_name.error_messages['required'] = _('Last name field is required')
    
        email = forms.CharField(required=True, max_length=50)
        email.error_messages['required'] = _('Email field is required')
    
        password = forms.CharField(required=True, max_length=50)
        password.error_messages['required'] = _('Password field is required')
    
        password2 = forms.CharField(required=True, max_length=50)
        password2.error_messages['required'] = _('Confirm password field is required')
        class Meta:
            model = User
            fields = ('username', 'first_name', 'last_name', 'email', 'password', 'password2')
    
    0 讨论(0)
  • 2020-12-04 10:18

    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.

    0 讨论(0)
提交回复
热议问题