Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom validator in a subclass that validates a parent field in Django

Tags:

django

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!

like image 226
brandon Avatar asked Dec 29 '25 20:12

brandon


1 Answers

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)
like image 160
Thomas Orozco Avatar answered Dec 31 '25 13:12

Thomas Orozco