如何在Django REST框架中修复UnicodeDecodeError?

huangapple go评论109阅读模式
英文:

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

  1. class ProductImage(models.Model):
  2. product = models.ForeignKey(Product, on_delete=models.CASCADE)
  3. image = models.ImageField(upload_to='product_images', width_field=None, height_field=None,
  4. max_length=250)
  5. default = models.BooleanField(verbose_name='Default Picture', default=False)
  6. def __str__(self):
  7. return '%s - %s' % (self.product.product_id, self.default)

这是我的serializers.py

  1. class ProductImageSerializer(serializers.ModelSerializer):
  2. product = serializers.PrimaryKeyRelatedField(many=False, queryset=Product.objects.all())
  3. class Meta:
  4. model = ProductImage
  5. fields = ['id', 'product', 'image', 'default']
  6. def to_representation(self, instance):
  7. if self.context['request'].method == 'GET':
  8. product = ProductSerializer(instance.product, many=False, context=self.context).data
  9. data = {
  10. 'id': instance.id,
  11. 'product': product,
  12. 'image': instance.image,
  13. 'default': instance.default,
  14. }
  15. return data
  16. return Serializer.to_representation(self, instance)

这是我的views.py

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

我认为根据我在几个StackOverflow帖子中搜索到的信息,问题是由于image字段引起的。

当我从serializers.pyto_representation函数中删除image字段后,这是删除后的截图:

如何在Django REST框架中修复UnicodeDecodeError?

我应该在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:

  1. class ProductImage(models.Model):
  2. product = models.ForeignKey(Product, on_delete=models.CASCADE)
  3. image = models.ImageField(upload_to='product_images', width_field=None, height_field=None,
  4. max_length=250)
  5. default = models.BooleanField(verbose_name='Default Picture', default=False)
  6. def __str__(self):
  7. return '%s - %s' % (self.product.product_id, self.default)

Here's my serializers.py:

  1. class ProductImageSerializer(serializers.ModelSerializer):
  2. product = serializers.PrimaryKeyRelatedField(many=False, queryset=Product.objects.all())
  3. class Meta:
  4. model = ProductImage
  5. fields = ['id', 'product', 'image', 'default']
  6. def to_representation(self, instance):
  7. if self.context['request'].method == 'GET':
  8. product = ProductSerializer(instance.product, many=False, context=self.context).data
  9. data = {
  10. 'id': instance.id,
  11. 'product': product,
  12. 'image': instance.image,
  13. 'default': instance.default,
  14. }
  15. return data
  16. return Serializer.to_representation(self, instance)

Here's my views.py:

  1. class ProductImageView(viewsets.ModelViewSet):
  2. queryset = ProductImage.objects.all()
  3. 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:

如何在Django REST框架中修复UnicodeDecodeError?

What should I add or edit in ProductImageSerializer to be able to show the image field properly?

答案1

得分: 11

尝试使用以下代码部分:

  1. instance.image.url instead of instance.image

并且对于完整的 URL 使用:

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

在阅读您的所有代码之后,您还可以这样做:

  1. class ProductImageSerializer(serializers.ModelSerializer):
  2. product = ProductSerializer()
  3. class Meta:
  4. model = ProductImage
  5. fields = ['id', 'product', 'image', 'default']
  6. # 删除 to_representation 函数

并且还可以在新的键 'images' 中显示与产品相关的图像:

  1. # 在您的产品序列化器中,将会是这样的
  2. class ProductImageSerializer(serializers.ModelSerializer):
  3. class Meta:
  4. model = ProductImage
  5. fields = ['id', 'image', 'default']
  6. class ProductSerializer(serializers.ModelSerializer):
  7. images = ProductImageSerializer(many=True)
  8. # 应该设置 many=True,因为每个产品可能有多个相关的图像
  9. class Meta:
  10. model = Product
  11. fields = [....., 'images']

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

英文:

try

  1. instance.image.url instead of instance.image

and for full url use

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

after reading all your code you can do this also

  1. class ProductImageSerializer(serializers.ModelSerializer):
  2. product = ProductSerializer()
  3. class Meta:
  4. model = ProductImage
  5. fields = ['id', 'product', 'image', 'default']
  6. # remove to_representation function

and also you can show images related to product in new key 'images'

  1. # in your product serializer it will be like this
  2. class ProductImageSerializer(serailizers.ModelSerializer):
  3. class Meta:
  4. model = ProductImage
  5. fields = ['id', 'image', 'default']
  6. class ProductSerializer(serializers.ModelSerilaizer):
  7. images = ProductImageSerializer(many=True)
  8. # should send many = True as it may be more than image related to every product
  9. class Meta:
  10. model = Product
  11. 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").

huangapple
  • 本文由 发表于 2020年1月3日 18:55:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定