3

I have a function that download a excel file in django:

 x= Y.objects.filter(pk__in=ids)
 response = HttpResponse(content_type='application/vnd.ms-excel')
 response['Content-Disposition'] = 'attachment; filename=Test.xlsx'
 test_data= WriteFile(x)
 response.write(test_data)
 return response

My objective it's to appear a message after this:

messages.success(request, 'Success!')

But I need to redirect after the return response because if not the message not appear and only appear if I refresh the page manually.

Any ideas how to make the message appear after download a file with the return response?

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
tg_dev3
  • 171
  • 3
  • 18

2 Answers2

0

You shouldn't necessarily need to redirect to show the message, though you could.

If instead of writing test_data to the response directly, you were to render a template response which included that data, then you could also include the success message in that template response.

If you do want to redirect, then you would need to:

  1. Store test_data in something persistent—e.g. a file on disk, or a database record
  2. Expose an endpoint to fetch this data from your persistent store and render it (along with any Django messages)
  3. Redirect to that endpoint using HttpResponseRedirect
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • Yes I can't do with this method... Any ideas? – tg_dev3 Aug 22 '18 at 12:11
  • Ah, I didn't read the question carefully enough. Missed the whole "Content-Disposition" part. In that case what I'd suggest is similar to what @brunodesthuilliers advises in his answer. – Dan Tao Aug 25 '18 at 19:12
0

You can only return one single response for a request, you cannot both redirect and return an attachment in the same response (well it might be technically legal - you'll have to carefully re-read the whole HTTP spec to find out -, but the client will most certainly ignore the response body when he gets a redirect status code, at least I newer saw a browser acting otherwise so far), and an "attachment" response will indeed not trigger a reload of the page you came for (the server cannot do this and a browser will not).

IOW, if you really want to have both a page refresh AND a download, you will need at least two views and some javascript - the first view creates the attachment and stores it somewhere, then return a html response with the "success" message, a link to the second view (with a reference to the attachment) and a js snippet that will trigger a click on this link, the second view only serves the attachment.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118