Django允许您定义模型字段的验证器,如下所示:
field = models.CharField(..,validators=[],..)
如果我允许用户将验证器附加到字段,那么最好的方法是什么?
例如,假设用户希望在此字段中应用RegexValidator,其中regex参数由它们定义。我将如何实现这种行为?
感谢。
答案 0 :(得分:1)
在单独的字段和包装器属性中以逗号分隔的名称列表如何:例如:
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