简体   繁体   中英

Django Rest Framework Serializers: Validating object.user is request.user

I'm working on a REST API with Django Rest Framework and in my ModelViewSet I need to validate that the current request.user has the right to edit a particular object.

I have found the part of the documentation that specifies how permissions work– but this is on the ViewSet side, and not the serializer side:

class FooViewSet(viewsets.ModelViewSet):
    model = Foo
    serializer_class = FooSerializer

    def get_queryset(self):
        return self.request.user.foos.all()

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def get_permissions(self):
        if self.action == "list":
            permission_classes = [permissions.IsAuthenticated]
        else:
            permission_classes = [IsObjectUser]
        return [permission() for permission in permission_classes]

This will work fine for 403ing when it's not the appropriate user, but I believe I should also be doing serializer-level validation? How can I get the object in question in my validate method to check against?

class FooSerializer(serializers.ModelSerializer):

    class Meta:
        model = Foo
        fields = [
            "type",
            "title",
            "description",
            "image",
        ]

    def validate(self, attrs):
        # <-- how can I get the object so I can check against the self.request.user?

My answer is that you shouldn't. Ideally your serializers don't know about the request. That's the views realm (with exceptions). Also, since user isn't specified in fields of FooSerializer it doesn't make sense to validate the user. If the user could be specified, then it should be validated.

   def validate(self, attrs):
        # <-- how can I get the object so I can check against the self.request.user?
         userobj=self.context['request'].user.
         print(attrs)
         title=attrs.get("title")
         enter code here

         attrs.update({'title': title})
         attrs = super().validate(attrs)
         return attrs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM