Django override default form error messages

前端 未结 10 1645
情歌与酒
情歌与酒 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: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",
        )
        ....
    

提交回复
热议问题