python - Is there another way to change the error message on a ModelForm for a validate_unique error? -
disregarding actual method use below parsing error messages since needs lots of improvement make more general-purpose, parsing error messages raised way of changing error message displayed?
specifically, i've removed 1 of fields modelform. when validate_unique run remove field validation described in this answer on so. error message django displays on form when validate_unique run says: 'x y , z exists.' z field manually removed modelform. want change error message because mentioning z, not-displayed field, confusing user has no way of changing z on form.
this feels fragile , 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: idx, err in enumerate(e.message_dict['__all__']): unique_together in self.instance._meta.unique_together: if 'a_field_not_shown_on_form' not in unique_together: continue if err.lower() == '{} {} , {} exists.'.format(self.instance.__class__.__name__, unique_together[0], unique_together[1]).lower(): e.message_dict['__all__'][idx] = '{} {} 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) # unique field field_name = self._meta.unique_together[0] field_label = capfirst(opts.get_field(field_name).verbose_name) # insert error error dict, sneaky return _(u"%(model_name)s %(field_label)s exists.") % { 'model_name': unicode(model_name), 'field_label': unicode(field_label) }
Comments
Post a Comment