【问题标题】:How to fix UnicodeDecodeError in Django REST Framework?如何修复 Django REST 框架中的 UnicodeDecodeError?
【发布时间】:2020-04-21 22:36:57
【问题描述】:

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

UnicodeDecodeError 位于 /api/product_images/
“utf-8”编解码器无法解码位置 0 中的字节 0xff:无效的起始字节
Unicode 错误提示
无法编码/解码的字符串是:����

这是我的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 字段而发生的。

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

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

【问题讨论】:

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


    【解决方案1】:

    试试

    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 将图像作为字符串列表获取

    【讨论】:

    • Mohamed Abd El-hameed 谢谢。您的答案非常详细,并提供了许多选择。我星期一回去工作时会检查它。干杯!
    【解决方案2】:

    我把Response(request.data)弄错了。
    如果您要发送图像文件,则也可能发生此类错误。
    所以再给一个Response("any-string-or-other-you-want")

    【讨论】:

      猜你喜欢
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      相关资源
      最近更新 更多