Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question