Danila Kulakov
Danila Kulakov

Reputation: 1142

Django REST Framework, image breaks on uploading

I have model Product:

class Product(models.Model):
    ...
    image = models.ImageField(
        upload_to=lambda instance, filename: 'images/{0}/{1}'.format(instance.id, filename),
        max_length=254, blank=True, null=True
    )
    ...

Then I have serializer:

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = (
            ...
            'image',
            ...
        )

And then I have views:

class ProductViewSet(BaseViewSet, viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    @detail_route(methods=['POST'])

    def upload_image(self, request, *args, **kwargs):
        upload = request.data['file']
        print(upload.name)
        product = self.get_object()
        product.image.delete()

        upload = request.data['file']
        product.image.save(upload.name, upload)

        return Response({'Location': product.image.url}, status=status.HTTP_201_CREATED)

Problem is only with images. On uploading images changes 'source code', and I can't open it, in the browser black window. Mp3 and PDF formats works fine. Why does it happens? Thank you.

Upvotes: 0

Views: 113

Answers (1)

Andrei Todo
Andrei Todo

Reputation: 39

Maybe the problem is with base64 images? In this case you should import ModelSerializer from drf_base64.serializers and inherit from that.

Upvotes: 1

Related Questions