如何使用序列化器处理图像

时间:2019-05-29 17:05:09

标签: django django-rest-framework django-generic-views

我在用户配置文件中上传图片时遇到了一些问题,它已经从用户那里扩展了,当我想通过邮递员上传图片时返回空值

序列化器:

class UserProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = UserProfile
        fields = ('user', 'bio', 'avatar')

    def validate(self, data):
        print(data)
        self.context['avatar'] = self.context['request'].FILES.get('avatar')
        return data

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = UserSerializer.create(UserSerializer(), validated_data=user_data)

        validated_data['avatar'] = self.context['avatar']
        validated_data['user'] = user

        profile = UserProfile.objects.create(**validated_data)
        profile.bio = validated_data["bio"]

        profile.save()
        return profile

模型:

class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, related_name='profile', on_delete=True)
    bio = models.CharField(max_length=50, blank=True)
    avatar = models.ImageField(upload_to="media", blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username

1 个答案:

答案 0 :(得分:0)

我找到了解决方法,应要求将django中的图片存储在内存中。文件

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)