0

I'm writing a custom validator that receives a list of validators, and checks if any of them passes, so you can easily check for things like this integer field should be lower than 10 or higher than 100. This is what I have so far:

class ValidateAnyOf(object):
    def __init__(self, *validators):
        self.validators = validators

    def __call__(self, value):
        errors = []
        for validator in self.validators:
            try:
                validator(value)
                return
            except ValidationError as e:
                errors.append(e.message)

        raise ValidationError('Combined validation failed:' + ','.join(errors))

class TestModel(models.Model):
    score = models.IntegerField(validators=[ValidateAnyOf(validators.MaxValueValidator(10),
                                                          validators.MinValueValidator(100))])

The logic is ok. The problem arises when none of the validators passes. I want to show a list of the errors, so I store in a list the messages from the exceptions. The problem is that e.message seems to be a django.utils.functional.__proxy__ object, instead of a string, so I can't join them to show the full error message.

How can I get the error message from each exception?

1 Answer 1

1

They are an instance of django.utils.functional.__proxy__ because the message of the Django core validators is translatable and wrapped in ugettext_lazy. I think you can use something like ", ".join(unicode(e) for e in errors) to force evaluation of the message.

Sign up to request clarification or add additional context in comments.

2 Comments

unicode(e.message) did the trick. I had to manually pass the params for the placeholders using errors.append(unicode(e.message) % e.params) and it worked.
You can also now use django.utils.encoding.force_text instead of unicode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.