Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix UnicodeDecodeError in Django REST Framework?

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:

enter image description here

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

like image 513
Nathan Avatar asked Jan 03 '20 10:01

Nathan


1 Answers

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

like image 151
Mohamed Abd El-hameed Avatar answered Nov 02 '22 15:11

Mohamed Abd El-hameed