I
I
Ivan2020-09-01 10:36:11
Django
Ivan, 2020-09-01 10:36:11

How to pass context to Class-based validator?

Hello. Can you please tell me how to pass additional context to the validator? You need to get the object instance in the validator. Specifically, get the value of one of the customer fields

class TestSerializer(serializers.ModelSerializer):
    deadline = serializers.DateTimeField(validators=[DeadlineValidator()])
    
    class Meta:
        model = Topic
        fields = ('customer',  'deadline', )

class DeadlineValidator:
    requires_context = True

    def __call__(self, value):

        if value < timezone.now():
            raise ValidationError('Error')

        return value


PS
def validate_deadline(self, value):... doesn't really fit, since this validator is reused in several places and I would like to follow the DRY principle

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan, 2020-09-01
@ATNC

class DeadlineValidator:
    requires_context = True

    def set_context(self, serializer_field):
        instance = serializer_field.parent.instance

    def __call__(self, value):

        if value < timezone.now():
            raise ValidationError('Error')

        return value

Found a solution

D
Dr. Bacon, 2020-09-01
@bacon

The docs say that with requires_context = True, another parameter appears in __call__, check what's in it, https://www.django-rest-framework.org/api-guide/va...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question