In Django I have a parent abstract class with a few common fields, and some subclasses that add more fields. In some of these subclasses I would like to add custom validators that validate fields on the parent class.
class Template(models.Model):
text = models.CharField(max_length=200)
class GlobalTemplate(Template):
function = models.ManyToManyField(Function, null=True, blank=True)
I can easily add them on the field in the parent class like this:
class Template(models.Model):
text = models.CharField(max_length=200, validators=[validate_custom])
But in this case I want to add the validator to my child class GlobalTemplate, but have it attached to the text field.
Is this possible in Django?
Thanks!
Field validators are stored in field.validators, it's a list, so you basically need to append your validators there.
To access the field instance, you'll have to play a little bit with the _meta attribute of your object (note that you're not supposed to play with this attribute, so when you update django, you'll have to check that it has not changed). Here's how you could do it:
def get_fields_dict(self):
return dict((field.name, field) for field in self._meta.fields)
def __init__(self, *args, **kwargs):
super(GlobalTeplate, self).__init__(*args, **kwargs)
text_field = self.get_fields_dict()['text']
text_field.validators.append(validate_custom)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With