Ryan
Ryan

Reputation: 842

How to set Content-Disposition header using Django Rest Framework

I am serving an image using the Django REST framework. Unfortunately it downloads instead of displays. I guess I have to set the header Content-Disposition = 'inline'. How do I do this in the View or the Renderer?

class ImageRenderer(renderers.BaseRenderer):
    media_type = 'image/*'
    format = '*'
    charset = None
    render_style = 'binary'

    def render(self, data, media_type=None, renderer_context=None):
        return data

class ImageView(APIView):
    renderer_classes = (ImageRenderer, )

    def get(self, request, format=None):
        image=MyImage.objects.get(id=1)
        image_file = image.thumbnail_png.file
        return Response(image)

Upvotes: 10

Views: 8016

Answers (2)

ldrg
ldrg

Reputation: 4491

Django 4.2 included a django.utils.http.content_disposition_header() to handle the encoding and formatting of the header for you. See docs.

Upvotes: 1

Ken4scholars
Ken4scholars

Reputation: 6296

According to this page in the Django docs, you can set the Content-Disposition header in this way:

response = Response(my_data, content_type='image/jpeg')
response['Content-Disposition'] = 'attachment; filename="foo.jpeg"'

Upvotes: 8

Related Questions