60

如何覆盖我项目中所有应用程序(或至少 1 个应用程序)的默认表单错误消息(例如:需要其他语言的错误消息)

谢谢!

4

9 回答 9

87

最简单的方法是为表单字段定义提供一组默认错误。表单字段可以为其指定一个命名参数。例如:

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)
    ....

希望这可以帮助。

于 2009-09-28T18:40:05.427 回答
8

要全局覆盖“必需”错误消息,请在字段上设置 default_error_messages 类属性:

# 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."),
}

这需要在实例化任何字段之前发生,例如通过将其包含在 settings.py 中。

于 2013-11-22T13:44:20.330 回答
7

也来自谷歌,我需要的是覆盖表单中所有字段的默认必需消息,而不是每次定义新表单字段时都传递 error_messages 参数。另外,我还没有准备好深入研究 i18n,这个应用程序不需要是多语言的。这篇博文中的评论与我想要的最接近:-

http://davedash.com/2008/11/28/custom-error-messages-for-django-forms/

对于所有需要消息的表单字段,这就是我所做的:-

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",
    )
    ....
于 2011-01-21T23:22:42.693 回答
3

你可能想看看 Django 出色的i18n 支持

于 2009-09-26T18:16:39.757 回答
3

嗯,似乎没有简单的解决方法来解决这个问题。

在浏览 Django 代码时,我发现默认错误消息被硬编码到每个表单字段类中,例如:

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).'),
    }

最简单的方法是使用error_messages参数,所以我不得不编写包装函数:

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)

如果有人知道这样做的更优雅的方式将非常感激看到它:)

谢谢!

于 2009-09-28T08:52:08.000 回答
3

假设我有BaseForm一些error_messages字典,例如:

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

我想覆盖其中一条错误消息:

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

基本上,只需覆盖其中一个字典值。我不确定它如何与国际化一起工作。

于 2012-12-31T22:30:44.073 回答
3

来自 ProDjango 的书:

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
于 2013-09-12T07:27:51.447 回答
-2
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.')
于 2019-01-05T07:30:05.170 回答
-6

由于此页面出现在搜索中,即使问题很旧,也可能值得添加我的 0.02 美元。(我还在习惯 Stack Overflow 的特殊礼仪。)

下划线(“_”)是 ugettext_lazy 的别名(如果这是正确的术语);只需查看带有“硬编码”消息的文件顶部的导入语句。然后,Django 的国际化文档应该会有所帮助,例如http://www.djangobook.com/en/2.0/chapter19/

于 2010-07-20T08:37:08.020 回答