我在views.py
中有一种可以下载文件的方法
我是通过HttpResponse['Content-Disposition']
构建的
附件:
response = HttpResponse(content_type='text/json')
response['Content-Disposition'] = 'attachment; filename="%s"' % (dgjf)
response.write(dgjson)
如果我的方法返回
response
,这可以正常工作但是,下载后,我想重定向到
我这样呈现的确认页面:
confirmMsg = render(request,'confirmation.html',context)
我通常会从相同的方法返回。
但是我如何获得响应才能下载和
重定向到确认?
最佳答案
您需要先重定向到“确认后确认”页面,然后再强制下载。您的后页将显示类似“您的下载应自动开始,如果没有单击则..等”之类的内容。
在下一页中,您可以通过Javascript,http-refresh或iframe启动下载。
Javascript,在您的页面后模板中插入:
<script>location.href="download/url/here";</script>
在页面后 View 中的http-refresh在返回之前先对HttpResponse进行注释:
response = render_to_response(...)
response['Refresh'] = "0;url=/download/url/here"
return response
..或将以下标记添加到您的后续页面的标题中(URL之前的0是重定向之前要等待的秒数):
<meta http-equiv="Refresh" content="0;url=/download/url/here">
一个iframe就是这样(您可能还需要删除边框等):
<iframe src="/download/url/here" style="width:0;height:0"></iframe>
所有这些背后的想法是,下载不会更改屏幕上的像素,因此一旦您拥有屏幕上的尾页,初始化下载将看起来像页面正在下载文件(而不是看起来像是在下载文件)。重定向-这实际上是在做的事情)。
关于django - 如何让django同时返回HttpResponse和呈现不同的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43688011/