是否有另一种方法可以在ModelForm上更改validate_unique错误的错误消息?

时间:2013-04-18 14:13:08

标签: python django django-forms

忽略我在下面用于解析错误消息的实际方法,因为它需要大量改进才能使它更通用,解析这样提出的错误消息是改变显示的错误消息的唯一方法吗?

具体来说,我已经从ModelForm中删除了一个字段。运行validate_unique时,我会按照this answer中的说明从SO中删除该字段。当运行validate_unique时,Django在表单上显示的错误消息说:'带有此Y和Z的X已经存在。'其中Z是我从ModelForm手动删除的字段。我想更改此错误消息,因为提及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)

1 个答案:

答案 0 :(得分:2)

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