实际上,我想将包含图像的嵌套json发送到在Django中创建用户个人资料图像,而解决的主要问题是我无法填充嵌套对象
这是我的json,以原始模式成功发布:
{
"id": 1,
"bio": "salam manam",
"user": {
"username": "amirlesani",
"first_name": "",
"password":"somepasword"
"last_name": "",
"email": ""
},
"user_type": {
"user_type": "br"
}
}
但是当我想要以这种方式填写表格数据时,它显示了这样的错误 user_type:此字段为必填项! 用户:此字段为必填项!
序列化器:
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer()
user_type = UserTypeSerializer()
images = ProfileImageSerializer(source='profileimage_set', many=True, read_only=True)
class Meta:
model = UserProfile
fields = ('id', 'bio', 'user', 'images', 'user_type')
def create(self, validated_data):
usertype = validated_data.pop('user_type')
type = UserTypeSerializer.create(UserTypeSerializer(), validated_data=usertype)
user_data = validated_data.pop('user')
user = UserSerializer.create(UserSerializer(), validated_data=user_data)
userprofile = UserProfile.objects.create(user=user, bio=validated_data.pop('bio'), user_type=type)
images_data = self.context.get('view').request.FILES
for image_data in images_data.values():
ProfileImage.objects.create(userprofile=userprofile, image=image_data, user_type=type)
userprofile.save()
return userprofile
答案 0 :(得分:0)
我找到了解决方案,您必须将imageUploader与嵌套的json区别开,并使用外键将您的图像连接到您的数据