带有重定向的Django HttpResponse [英] Django HttpResponse with redirect

查看:65
本文介绍了带有重定向的Django HttpResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能,可以在Django中下载excel文件:

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!')

但是我需要在 return response 之后重定向,因为如果没有,则该消息不会出现,只有在我手动刷新页面时才会出现.

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?

推荐答案

您只能为一个请求返回一个响应,不能同时重定向和返回同一响应中的附件(可能 从技术上讲是合法的-您必须仔细阅读整个HTTP规范以了解信息-但客户端在获得重定向状态代码时肯定会忽略响应正文,至少我较新地看到浏览器以其他方式运行到目前为止),并且附件"响应确实不会触发您所访问页面的重新加载(服务器无法执行此操作,浏览器也无法执行).

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,如果您真的要刷新页面并下载文件,则至少需要两个视图和一些javascript-第一个视图创建附件并将其存储在某个地方,然后返回一个带有成功"消息的html响应,一个指向第二个视图的链接(带有对附件的引用)以及一个将触发对该链接的点击的js代码段,第二个视图仅用于附件.

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.

这篇关于带有重定向的Django HttpResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆