我有以下视图功能,可以创建一个zip文件并将其发送到客户端。 除了zip文件,我还想使用django.contrib.messages向用户显示成功消息。 我的问题是如果我使用HttpResponseRedirect客户端获取消息但不获取zip文件。 另一方面,如果我使用HttpResponse客户端获取zip文件但不获取消息。 有没有办法实现这两种功能?
import os
from StringIO import StringIO
from zipfile import ZipFile
from django.contrib import messages
from django.http import HttpResponseNotAllowed, HttpResponse, HttpResponseRedirect
...
def export_all(request):
"""
Create a zip file and return it for download.
"""
in_memory = StringIO()
zip = ZipFile(in_memory, "a")
exported_date = datetime.datetime.now().strftime('%d-%h-%Y')
zip_file_name = 'my_files_' + exported_date
a_to_export = A.objects.all().order_by('name')
b_to_export = B.objects.all().order_by('name')
# add relevant content to the zip file
export_a(a_to_export, zip)
export_b(b_to_export, zip)
zip.close()
response = HttpResponse(mimetype="application/zip")
response["Content-Disposition"] = "attachment; filename=" + zip_file_name + '.zip'
in_memory.seek(0)
response.write(in_memory.read())
messages.success(request, 'All files exported successfully.')
# If I use HttpResponseRedirect client gets the message but not the zip file.
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
# If I use HttpResponse client gets the zip file but not the message.
return response