獲取登陸用戶信息

錯誤信息python

AssertionError: Expected view UserListUpdate to be called with a URL keyword a
rgument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on
 the view correctly.

代碼函數

# views.py
class UserUpdate(UpdateAPIView):
    """
    用戶更改密碼
    """
    queryset = User.objects.all()
    serializer_class = UserUpdateSerializer
    permission_classes = (IsAuthenticated,)
    
# serializers.py
class UserUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        ....
    # 更新
    def update(self, instance, validated_data):
        instance.username = validated_data.get('username')
        instance.set_password(validated_data.get('password'))
        instance.save()
        return validated_data

  • 此次的需求是在用戶登陸的狀況下,可以更改本人的密碼,可是當發送put請求後會拋出異常,主要意思大概就是缺乏主鍵(pk)

解決思路

  • 咱們須要在視圖中獲取當前登陸用戶信息
  • 而後傳入序列化函數中
class UserUpdate(UpdateAPIView):
    """
    用戶更改密碼
    """
    queryset = User.objects.all()
    serializer_class = UserUpdateSerializer
    permission_classes = (IsAuthenticated,)
    # 獲取當前已經登陸用戶信息  傳入
    def get_object(self):
        return self.request.user
相關文章
相關標籤/搜索