Skip to content Skip to sidebar Skip to footer

Return Image Using Django Rest Framework Render

I uploaded images using Django REST Framework. Now I'm trying to return the same image as response.views.py class ImageUploadView(viewsets.ModelViewSet): queryset = ImageModel.

Solution 1:

I had the same issue and spent hours on it and I came up with a solution. Here's how you do it:

1. Create Custom Renderers

At first, you need to create something called custom renderers. Here's the link to the REST Framework's Renderers Documentation if you wanna know more about what renderers are and how to make custom renderers. In this case, we'll have to make custom renderers for .jpg and .png files. For this, I would suggest you create a file called custom_renderers.py and copy the following code into it:

custom_renderers.py

from rest_framework import renderers

classJPEGRenderer(renderers.BaseRenderer):
    media_type = 'image/jpeg'format = 'jpg'
    charset = None
    render_style = 'binary'defrender(self, data, media_type=None, renderer_context=None):
        return data

classPNGRenderer(renderers.BaseRenderer):
    media_type = 'image/png'format = 'png'
    charset = None
    render_style = 'binary'defrender(self, data, media_type=None, renderer_context=None):
        return data

2. Import the renderers and include them in your view by

After this, you've got to import the renders that you've just made and include them in your view within the attribute renderer_classes = [JPEGRenderer, PNGRenderer] if you are using class-based views (or if you are using method-based views, you've got to include them under the decorator @renderer_classes())

3. The rest of your view and the return statement

If you're serving an image or any kind of in your view, you've got to first open the image or the file by using .open() next to the image object that you've received as a response field of your query, and then use a FileWrapper() to wrap the image before you send it (The reason I was getting a small black box in the response just like you was that I had not opened the image before sending it and also hadn't used a FileWrapper()). So, your response goes like - return Response(FileWrapper(ImageModel.objects.get(id=serializer.data['id'])['image'].open())

I did not specify the return type as the return type was automatically determined in my case. Therefore, your views.py will finally be like:

## All the other necessary importsfrom path.to.custom_renderers import JPEGRenderer, PNGRenderer
from wsgiref.util import FileWrapper

#Also, I think this should rather be ImageDownloadView as the client would be downloading the imageclassImageUploadView(viewsets.ModelViewSet):
    renderer_classes = [JPEGRenderer, PNGRenderer]

    queryset = ImageModel.objects.all()
    serializer_class = ImageSerializer

    defcreate(self, request, *args, **kwargs):
        userID = (request.data.get('userID'))
        serializer = self.get_serializer(data=request.data)
        ifnot UserModel.objects.filter(id=userID).exists():
            return Response(data={"detail": "Invalid UserID"})
        else:
            if serializer.is_valid():
                serializer.save()                
                return Response(FileWrapper(ImageModel.objects.get(id=serializer.data['id'])['image'].open())
                # You can also specify the content_type in your responsereturn Response(data={"detail": "Serializer Error"})

Cheers!!

Post a Comment for "Return Image Using Django Rest Framework Render"