I need to send a pdf file and some other parameters in response to a get API call using django rest framework.
How can I do it?
I tried this but it gives an error
If you really need to serve binary files directly from your backend (e.g. when they're being generated dynamically) you can use a custom renderer:
from rest_framework.renderers import BaseRenderer
class BinaryFileRenderer(BaseRenderer):
media_type = 'application/octet-stream'
format = None
charset = None
render_style = 'binary'
def render(self, data, media_type=None, renderer_context=None):
return data
Then use it in your action in a viewset:
@detail_route(methods=['get'], renderer_classes=(BinaryFileRenderer,))
def download(self, request, *args, **kwargs):
with open('/path/to/file.pdf', 'rb') as report:
return Response(
report.read(),
headers={'Content-Disposition': 'attachment; filename="file.pdf"'},
content_type='application/pdf')