Python 是否有其他方法可以更改ModelForm上针对validate_唯一错误的错误消息?
忽略我在下面使用的解析错误消息的实际方法,因为它需要大量的改进以使其更通用,解析这样引发的错误消息是否是更改显示的错误消息的唯一方法 具体来说,我已经从模型表单中删除了一个字段。当运行validate_unique时,我将从验证中删除该字段,如on SO中所述。当运行validate_unique时,Django在表单上显示的错误消息是:“带有Y和Z的X已经存在。”其中Z是我从模型表单中手动删除的字段。我想更改此错误消息,因为提到Z,不显示字段,这让无法更改此表单上的Z的用户感到困惑 这感觉很脆弱和粗糙Python 是否有其他方法可以更改ModelForm上针对validate_唯一错误的错误消息?,python,django,django-forms,Python,Django,Django Forms,忽略我在下面使用的解析错误消息的实际方法,因为它需要大量的改进以使其更通用,解析这样引发的错误消息是否是更改显示的错误消息的唯一方法 具体来说,我已经从模型表单中删除了一个字段。当运行validate_unique时,我将从验证中删除该字段,如on SO中所述。当运行validate_unique时,Django在表单上显示的错误消息是:“带有Y和Z的X已经存在。”其中Z是我从模型表单中手动删除的字段。我想更改此错误消息,因为提到Z,不显示字段,这让无法更改此表单上的Z的用户感到困惑 这感觉很脆
def validate_unique(self):
exclude = self._get_validation_exclusions()
exclude.remove('a_field_not_shown_on_form')
try:
self.instance.validate_unique(exclude=exclude)
except ValidationError, e:
if '__all__' in e.message_dict:
for idx, err in enumerate(e.message_dict['__all__']):
for unique_together in self.instance._meta.unique_together:
if 'a_field_not_shown_on_form' not in unique_together:
continue
if err.lower() == '{} with this {} and {} already exists.'.format(self.instance.__class__.__name__,
unique_together[0],
unique_together[1]).lower():
e.message_dict['__all__'][idx] = '{} with this {} already exists in {}'.format(self.instance.__class__.__name__,
unique_together[0].capitalize(),
self.instance.complex.name)
self._update_errors(e.message_dict)
把我推向正确的方向。谢谢我把这个和这个结合起来:
from django.utils.text import capfirst
class YourModel(models.Model):
# fields
def unique_error_message(self, model_class, unique_check):
opts = model_class._meta
model_name = capfirst(opts.verbose_name)
# A unique field
field_name = self._meta.unique_together[0]
field_label = capfirst(opts.get_field(field_name).verbose_name)
# Insert the error into the error dict, very sneaky
return _(u"%(model_name)s with this %(field_label)s already exists.") % {
'model_name': unicode(model_name),
'field_label': unicode(field_label)
}