Django override default form error messages

前端 未结 10 1619
情歌与酒
情歌与酒 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:26

    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/

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

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

    0 讨论(0)
  • 2020-12-04 10:29
    from django import forms
    from django.utils.translation import gettext as _
    
    
    class MyForm(forms.Form):
         # create form field
         subject = forms.CharField(required=True)
    
         # override one specific error message and leave the others unchanged
         # use gettext for translation
         subject.error_messages['required'] = _('Please enter a subject below.')
    
    0 讨论(0)
  • 2020-12-04 10:35

    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.

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