How to set current user to user field in Django Rest Framework?

前端 未结 9 2012
后悔当初
后悔当初 2020-12-02 15:30

I have the following code working perfectly. I can create a Post object from DRF panel by selecting an image and a user. However I want DRF to populate the user

9条回答
  •  悲&欢浪女
    2020-12-02 15:42

    It depends on your use case. If you want it to be "write-only", meaning DRF automatically populates the field on write and doesn't return the User on read, the most straight-forward implementation according to the docs would be with a HiddenField:

    class PhotoListAPIView(generics.ListCreateAPIView):
        user = serializers.HiddenField(
            default=serializers.CurrentUserDefault(),
        )
    

    If you want want it to be readable, you could use a PrimaryKeyRelatedField while being careful that your serializer pre-populates the field on write - otherwise a user could set the user field pointing to some other random User.

    class PhotoListAPIView(generics.ListCreateAPIView):
        user = serializers.PrimaryKeyRelatedField(
            # set it to read_only as we're handling the writing part ourselves
            read_only=True,
        )
    
        def perform_create(self, serializer):
            serializer.save(user=self.request.user)
    

    Finally, note that if you're using the more verbose APIView instead of generics.ListCreateAPIView, you have to overwrite create instead of perform_create like so:

    class PhotoListAPIView(generics.ListCreateAPIView):
        user = serializers.PrimaryKeyRelatedField(
            read_only=True,
        )
    
        def create(self, validated_data):
            # add the current User to the validated_data dict and call
            # the super method which basically only creates a model
            # instance with that data
            validated_data['user'] = self.request.user
            return super(PhotoListAPIView, self).create(validated_data)
    

提交回复
热议问题