Django Rest Framework:将用户从视图传递到序列化器

时间:2019-04-18 16:14:34

标签: django django-rest-framework

我对用户更改密码有这样的看法:

class ChangePasswordView(generics.UpdateAPIView):
    serializer_class = ChangePasswordSerializer
    permission_classes = [IsAuthenticated]

        def put(self, request, *args, **kwargs):
            data = request.data.copy()
            data['user'] = self.request.user
            serializer = self.get_serializer(data=data)
            serializer.is_valid(raise_exception=True)
            user = serializer.validated_data['user']
            user.set_password(serializer.validated_data["new_password"])
            user.save()
            return Response(status=status.HTTP_204_NO_CONTENT)

此视图的序列化器如下所示:

class ChangePasswordSerializer(serializers.Serializer):
    old_password = serializers.CharField()
    new_password = serializers.CharField()
    new_password_retyped = serializers.CharField()

    def validate(self, data):
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        new_password_retyped = data.get('new_password_retyped')
        user = data.get('user')

        # misc validation checks

        data['user'] = user
        return data

我的问题是用户对象没有传递给序列化器,尝试打印它以查看put中的数据内容:

<QueryDict: {'old_password': ['testpassword'], 'new_password': ['testpassword1'], 'new_password_retyped': ['testpassword1'], 'user': [<User: root>]}>

和内部序列化器:

OrderedDict([('old_password', 'testpassword'), ('new_password', 'testpassword1'), ('new_password_retyped', 'testpassword1')])

如您所见,用户丢失。首先,我认为可能与将对象传递给序列化程序有关,因此我将data['user'] = self.request.user更改为data['user'] = self.request.user.username,因此它只会传递带有用户名的字符串,而没有运气

1 个答案:

答案 0 :(得分:3)

您不能通过这种方式将用户传递给序列化程序,因为序列化程序会删除不是相关事件的数据。尝试做这样的事情。

class ChangePasswordSerializer(serializers.Serializer):
    old_password = serializers.CharField()
    new_password = serializers.CharField()
    new_password_retyped = serializers.CharField()

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super().__init__(*args, **kwargs)

    def validate(self, data):
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        new_password_retyped = data.get('new_password_retyped')
        user = self.user

        # misc validation checks

        data['user'] = user
        return data

并将用户分别传递给序列化器。

self.get_serializer(data=data, user=self.request.user)