在python django rest框架中编辑用户详细信息

时间:2017-06-23 22:51:59

标签: python django api django-rest-framework

我需要使用API​​View类来编辑用户详细信息的代码,例如first_name,last_name。下面给出了serializers.py和views.py,但它没有根据用户的详细信息进行更改。我正在传递令牌以进行用户身份验证任何帮助将不胜感激。

Serializers.py

class UserEditSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True)
    first_name = serializers.CharField(required=True)
    last_name = serializers.CharField(required=True)

    def update(self, validated_data, instance):

        instance.first_name = validated_data.get('first_name')
        instance.email = validated_data.get('email')
        instance.last_name = validated_data.get('last_name')
        instance.save()
        return instance()

Views.py

class UserEditProfile(APIView):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)

    def get_object(self):
        return self.request.user

    def post(self, request):
        self.object = self.get_object()
        serializer = UserEditSerializer(data=request.data)
        if serializer.is_valid():
            self.object.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

2 个答案:

答案 0 :(得分:0)

如果您不提供用户,序列化工具如何知道必须更新用户?

    serializer = UserEditSerializer(data=request.data)

应该是:

    serializer = UserEditSerializer(self.object, data=request.data)

编辑: 另外,在return instance

之后删除()

答案 1 :(得分:0)

此视图将有效。谢谢Linovia

PluginDemo