0

I have a method in my views.py that I've constructed with a http response

 # # content-type of response
    response = HttpResponse(content_type='application/ms-excel')

    # #decide file name
    response['Content-Disposition'] = 'attachment; filename="ThePythonDjango.xls"'
#adding new sheets and data
                new_wb = xlwt.Workbook(encoding='utf-8')
new_wb.save(response)

This works fine if I only have response in my return But I also want to return a render

return  render(request, 'uploadpage/upload.html', {"excel_data": seller_info, "message":message, "errormessage":errormessage})

I was wondering if there's a way to do that

to3
  • 29
  • 5
  • 1
    It is impossible to make two responses from one :). Generaly it should first "return the render", and the rendered page should start the download via another HTTP request to a (separate) view. Maybe you could reword the question like "Hot to display a page and start the file download from it in django?". – ei-grad Oct 24 '19 at 17:03
  • i took your suggestion haha – to3 Oct 24 '19 at 17:31

1 Answers1

0

It could be done by making the view behave differently on the existence of some query parameter, the download parameter, for example. Actually, it would be equivalent to having two separate views:

  1. The first view should return the rendered HTML response, which automatically starts the file download. For example via an iframe, just put this code into the template:

    <iframe width="1" height="1" frameborder="0" src="?download"></iframe>
    

    You can see some other methods to start automatic download here: How to start automatic download of a file in Internet Explorer?

  2. The second view should contain your XLS generation code and return the HttpResponse with the XLS contents.

Combining this into a single view could look like:

def xls_download_view(request):
    if 'download' in request.GET:
        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename="ThePythonDjango.xls"'
        new_wb = xlwt.Workbook(encoding='utf-8')
        ...
        new_wb.save(response)
        return response
    else:
        ...
        return render(...)
ei-grad
  • 792
  • 7
  • 19