Django HttpResponse with redirect

瘦欲@ 提交于 2021-02-10 06:14:07

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/51965240/django-httpresponse-with-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!