您好,您是静止框架的新手,并且遇到了更新用户配置文件的问题,我将用户序列化程序插入了序列化程序中。我的sprofile序列化器看起来像这样
class CompanyOwnerSerializer(serializers.ModelSerializer):
user = UserSerializer(many=False, required=False)
profile_pic = serializers.FileField(source='profile', required=False)
class Meta:
model = CompanyOwner
fields = "__all__"
def update(self, instance, validated_data):
data_user = validated_data.pop('user')
instance.gender = validated_data.get('gender', instance.gender)
instance.job_title = validated_data.get('job_title', instance.job_title)
instance.description = validated_data.get('description', instance.description)
instance.location = validated_data.get('location', instance.location)
instance.address = validated_data.get('address', instance.address)
instance.longitude = validated_data.get('longitude', instance.longitude)
instance.latitude = validated_data.get('longitude', instance.latitude)
instance.save()
if 'id' in data_user.keys():
current_user = User.objects.get(id=data_user['id'])
current_user.username = data_user.get('username', current_user.username)
current_user.first_name = data_user.get('first_name', current_user.first_name)
current_user.last_name = data_user.get('username', current_user.last_name)
current_user.save()
return instance
我的问题是,当我从邮递员发送数据时出现错误
KeyError at /profile-update/1/
'user'
Request Method: PUT
我发送的数据是
"user": {
"username": "kim_apps",
"first_name": "",
"email": "kimrop@examplemail.com",
"last_name": "",
"date_joined": "2019-06-06T21:00:32.612338Z"
},
"gender": "",
"job_title": "",
"description": "",
"location": "KE",
"address": "",
"longitude": 36.23456,
"latitude": -1.234567
}
有人可以帮助我,控制台显示找不到行中的密钥 user
data_user = validated_data.pop('user')
我尝试打印validated_data,但它提供了一个空字典
我更改了问题标题,因为我认为这是问题所在
答案 0 :(得分:0)
感谢检查,我终于找到了解决方案,现在可以正常工作了,我将更新功能从序列化器移到了这样的视图中
class ProfileUpdateView(UpdateAPIView):
queryset = CompanyOwner.objects.all()
serializer_class = CompanyOwnerSerializer
def update(self, request, *args, **kwargs):
instance = self.get_object()
validated_data = request.data
print(validated_data)
data_user = validated_data.pop('user')
instance.gender = validated_data.get('gender', instance.gender)
instance.job_title = validated_data.get('job_title', instance.job_title)
instance.description = validated_data.get('description', instance.description)
instance.location = validated_data.get('location', instance.location)
instance.address = validated_data.get('address', instance.address)
instance.longitude = validated_data.get('longitude', instance.longitude)
instance.latitude = validated_data.get('longitude', instance.latitude)
instance.save()
if 'id' in data_user.keys():
current_user = User.objects.get(id=data_user['id'])
current_user.username = data_user.get('username', current_user.username)
current_user.first_name = data_user.get('first_name', current_user.first_name)
current_user.last_name = data_user.get('username', current_user.last_name)
current_user.save()
我不明白,但我认为他们是一样的。无论如何,这是我想要的。