python - 如何修复 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_representation
serializers.py
我应该添加或编辑什么ProductImageSerializer
才能正确显示该image
字段?
解决方案
尝试
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 将图像作为字符串列表获取
推荐阅读
- mysql - 根据mysql中的条件从另一个表更新一个表
- python - 在 tensorflow 中提取 MNIST:zlib.error:解压缩数据时出现错误 -3:无效距离太远
- javascript - 交叉点观察者 polyfill 不工作 Safari
- amazon-web-services - 仅 Athena 上一个数据库的 IAM CreateTable 权限
- android - Mixpanel 人员跟踪不起作用
- cassandra - 2 节点集群不复制数据
- javascript - 同一页面上的两个灯箱重叠
- react-native - 从后代 React Native FlatList 重新渲染
- javascript - Node.js - 套接字挂断了 HTTP 请求
- coq - 如何使用循环/交换策略?