英文:
How to fix UnicodeDecodeError in Django REST Framework?
问题
我想在可浏览的API中显示ProductImageSerializer
。但是我遇到了这个错误:
UnicodeDecodeError at /api/product_images/
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Unicode error hint
The string that could not be encoded/decoded was: �����
这是我的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
字段?
英文:
I want to show ProductImageSerializer
in the browsable API. But I got this error:
> UnicodeDecodeError at /api/product_images/
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Unicode error hint
The string that could not be encoded/decoded was: �����
Here's my 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)
Here's my 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)
Here's my views.py
:
class ProductImageView(viewsets.ModelViewSet):
queryset = ProductImage.objects.all()
serializer_class = ProductImageSerializer
I think from what I've searched on several StackOverflow posts is that the problem occurs because of the image
field.
Here's the screenshot when I removed image
field from to_representation
function in serializers.py
:
What should I add or edit in ProductImageSerializer
to be able to show the image
field properly?
答案1
得分: 11
尝试使用以下代码部分:
instance.image.url instead of instance.image
并且对于完整的 URL 使用:
self.context['request'].build_absolute_uri(instance.image.url)
在阅读您的所有代码之后,您还可以这样做:
class ProductImageSerializer(serializers.ModelSerializer):
product = ProductSerializer()
class Meta:
model = ProductImage
fields = ['id', 'product', 'image', 'default']
# 删除 to_representation 函数
并且还可以在新的键 'images' 中显示与产品相关的图像:
# 在您的产品序列化器中,将会是这样的
class ProductImageSerializer(serializers.ModelSerializer):
class Meta:
model = ProductImage
fields = ['id', 'image', 'default']
class ProductSerializer(serializers.ModelSerializer):
images = ProductImageSerializer(many=True)
# 应该设置 many=True,因为每个产品可能有多个相关的图像
class Meta:
model = Product
fields = [....., 'images']
您还可以使用 SerializerMethodField 来获取图像列表作为字符串。
英文:
try
instance.image.url instead of instance.image
and for full url use
self.context['request'].build_absolute_uri(instance.image.url)
after reading all your code you can do this also
class ProductImageSerializer(serializers.ModelSerializer):
product = ProductSerializer()
class Meta:
model = ProductImage
fields = ['id', 'product', 'image', 'default']
# remove to_representation function
and also you can show images related to product in new key 'images'
# 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']
you can also user SerializerMethodField to get images as a list of string
答案2
得分: 0
我犯了一个错误,对于 Response(request.data)
。
如果您正在发送图像文件,也可能会发生这种类型的错误。
因此,请提供另一个 Response("任何字符串或其他您想要的")
。
英文:
I had made a mistake for Response(request.data)
.
If you are sending image-file then this type of error can also occur.
So give another Response("any-string-or-other-you-want")
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论