【问题标题】:Is there another way to change the error message on a ModelForm for a validate_unique error?是否有另一种方法可以将 ModelForm 上的错误消息更改为 validate_unique 错误?
【发布时间】:2013-04-11 17:04:16
【问题描述】:

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

具体来说,我已从 ModelForm 中删除了其中一个字段。当 validate_unique 运行时,我从验证中删除该字段,如 SO 上的this answer 中所述。运行 validate_unique 时 Django 在表单上显示的错误消息说:“带有这个 Y 和 Z 的 X 已经存在。”其中 Z 是我从 ModelForm 中手动删除的字段。我想更改此错误消息,因为提及未显示的字段 Z 会使无法更改此表单上的 Z 的用户感到困惑。

这感觉很脆弱和hacky。

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)

【问题讨论】:

    标签: python django django-forms


    【解决方案1】:
    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)
            }
    

    【讨论】:

    猜你喜欢
    • 2019-01-20
    • 2020-06-02
    • 2021-02-01
    • 2019-11-30
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    相关资源
    最近更新 更多