如何为项目中的所有应用程序(或至少1个应用程序)覆盖默认表单错误消息(例如:需要使用其他语言)
谢谢!
答案 0 :(得分:69)
最简单的方法是将一组默认错误提供给表单字段定义。表单字段可以为其指定一个命名参数。例如:
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)
....
希望这有帮助。
答案 1 :(得分:8)
要全局覆盖“required”错误消息,请在Field上设置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中。
答案 2 :(得分:6)
也来自谷歌,我需要的是覆盖表单中所有字段的默认必需消息,而不是每次定义新表单字段时传递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",
)
....
答案 3 :(得分:3)
你可能想看看Django的优秀i18n support。
答案 4 :(得分:3)
Wile浏览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)
如果smdb知道更加优雅的方式,那么真的很容易看到它:)
谢谢!
答案 5 :(得分: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
答案 6 :(得分:2)
我说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!!!'
基本上,只需覆盖其中一个字典值。我不确定它如何与国际化合作。
答案 7 :(得分:0)
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.')
答案 8 :(得分:0)
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')
答案 9 :(得分:-5)
由于此页面出现在搜索中,或许值得添加我的0.02美元,即使这个问题已经过时了。 (我仍然习惯Stack Overflow的特殊礼仪。)
下划线(“_”)是ugettext_lazy的别名(如果这是正确的术语);只需使用“硬编码”消息查看文件顶部的import语句即可。然后,Django的国际化文档应该有帮助,例如http://www.djangobook.com/en/2.0/chapter19/