AttributeError Exception: Serializer has no attribute request in DRF

Question:

I have written following code in serializer where I am validating data:

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.MyClass
        fields = "__all__"

    def validate(self, data):
        role = data["role"]
        roles = models.Role.objects.filter(
       -->(exception) organization=self.request.user.organization
        )
        if role not in roles:
            raise serializers.ValidationError("Invlid role selected")
        return data  

But I am getting following exception:

‘MySerializer’ object has no attribute ‘request’.
And it is coming in the mentioned line.
I want to access current user in validate function. How can I do that?

Asked By: Waleed Farrukh

||

Answers:

If the request is provided in the context, which a ModelViewSet for example does, you can access this with:

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.MyClass
        fields = '__all__'

    def validate(self, data):
        role = data['role']
        request = self.context['request']
        roles = models.Role.objects.filter(
            organization__user=request.user
        ).distinct()
        if role not in roles:
            raise serializers.ValidationError('Invalid role selected')
        return data
Answered By: Willem Van Onsem