Waleed Farrukh
Waleed Farrukh

Reputation: 315

AttributeError Exception: Serializer has no attribute request in DRF

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?

Upvotes: 1

Views: 78

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477749

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

Upvotes: 3

Related Questions