How to return generated file download with Django REST Framework?

后端 未结 5 1360
清歌不尽
清歌不尽 2021-02-04 03:20

I need to return generated file download as a Django REST Framework response. I tried the following:

def retrieve(self, request, *args, **kwargs):
    template =         


        
5条回答
  •  無奈伤痛
    2021-02-04 04:06

    For me, using Python 3.6, Django 3.0, and DRF 3.10, The problem came from using the wrong type of response. I needed to use a django.http.HttpResponse, as seen below:

    from django.http import HttpResponse
    ...
    with open('file.csv', 'r') as file:
        response = HttpResponse(file, content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=file.csv'
        return response
    

提交回复
热议问题