【发布时间】: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