Reputation: 139
Django lets you define validators of a model field like this:
field = models.CharField(..,validators=[],..)
If I were to allow users to attach validators to a field, what would be the best way?
For instance, let's say the user would like to apply a RegexValidator in this field where the regex parameter is defined by them. How would I achive that behavior?
Thanks.
Upvotes: 1
Views: 110
Reputation: 19114
How about a comma-separated list of names in a separate field and a wrapper property, e.g.:
import django.core.validators as validator_module
# Build a map of available validators. This code is not foolproof
# and might be better as a static dict, but it gives the idea.
validator_map = {}
for name, obj in validator_module.__dict__.items():
if name.startswith('validate') pr name.endswith('Validator'):
validator_map[name] = obj
class MyModel(Model):
value = CharField()
value_validators = TextField()
def set_value(self, value):
'Run validators and store the value'
vnames = self.value_validators.split(',')
for vname in vnames:
validator = validator_map[vname]
validator(value)
self.value = value
Upvotes: 1