首页 > 解决方案 > 如何修复 Django REST 框架中的 UnicodeDecodeError?

问题描述

我想ProductImageSerializer在可浏览的 API 中显示。但我得到了这个错误:

UnicodeDecodeError at /api/product_images/
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Unicode error hint
无法编码/解码的字符串是:����

这是我的models.py

class ProductImage(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='product_images', width_field=None, height_field=None,
                              max_length=250)
    default = models.BooleanField(verbose_name='Default Picture', default=False)

    def __str__(self):
        return '%s - %s' % (self.product.product_id, self.default)

这是我的serializers.py

class ProductImageSerializer(serializers.ModelSerializer):
    product = serializers.PrimaryKeyRelatedField(many=False, queryset=Product.objects.all())

    class Meta:
        model = ProductImage
        fields = ['id', 'product', 'image', 'default']

    def to_representation(self, instance):
        if self.context['request'].method == 'GET':
            product = ProductSerializer(instance.product, many=False, context=self.context).data
            data = {
                'id': instance.id,
                'product': product,
                'image': instance.image,
                'default': instance.default,
            }
            return data
        return Serializer.to_representation(self, instance)

这是我的views.py

class ProductImageView(viewsets.ModelViewSet):
    queryset = ProductImage.objects.all()
    serializer_class = ProductImageSerializer

我认为从我在几个 StackOverflow 帖子上搜索的内容来看,问题是由于该image字段而发生的。

这是我从函数中删除image字段时的屏幕截图: to_representationserializers.py

在此处输入图像描述

我应该添加或编辑什么ProductImageSerializer才能正确显示该image字段?

标签: pythondjangodjango-rest-frameworkdjango-views

解决方案


尝试

instance.image.url instead of instance.image 

并用于完整的网址

self.context['request'].build_absolute_uri(instance.image.url)

阅读完所有代码后,您也可以这样做


class ProductImageSerializer(serializers.ModelSerializer):
    product = ProductSerializer()

    class Meta:
        model = ProductImage
        fields = ['id', 'product', 'image', 'default']
    # remove to_representation function

您还可以在新的关键“图像”中显示与产品相关的图像

# in your product serializer it will be like this
class ProductImageSerializer(serailizers.ModelSerializer):
    class Meta:
        model = ProductImage
        fields = ['id', 'image', 'default']

class ProductSerializer(serializers.ModelSerilaizer):
    images = ProductImageSerializer(many=True)
    # should send many = True as it may be more than image related to every product 
    class Meta:
        model = Product
        fields = [....., 'images']

您还可以使用 SerializerMethodField 将图像作为字符串列表获取


推荐阅读