python - django:触发下载后重定向到另一个页面
问题描述
我希望用户在触发文件下载后被重定向到另一个页面。我该怎么做?下面是我关于如何触发下载的代码。或者,我如何将在第一个网页中创建的数据框解析为用户被重定向到的网页然后触发下载?任何帮助表示赞赏。谢谢!
from django.shortcuts import render
from django.http import HttpResponse
from .forms import *
from .functions import *
from . import models
def index(request):
if request.method == 'POST':
# upload file
file=request.FILES['excelfile']
df=createDF(file)
# write to xlsx and trigger download
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename="somefile.xlsx")
df.to_excel(response, index=False)
return response
# render form for upload
return render(request, 'webpage/index.html')
解决方案
您可以为您提到的数据框创建一个视图,在 urls.py 文件中注册该视图,并且您可以在发生某些事情后在重定向方法中使用这个新视图,例如使用单击下载按钮重定向到带有数据框的新页面并开始下载或者可能在最后一个视图中已经开始下载。
def dataframe(request):
# code to generate your dataframe, not sure how it works with your data.
return render(request, 'your_dataframe_template.html')
里面的 urls.py
urlpatterns = [
path('dataframeurl/', views.dataframe, name='dataframecoolname') # use some better name in the name argument
]
现在您可以使用name
重定向方法在视图中使用参数。
# the redirect would be something like this
def download_view(request):
# some logic you want, then...
return redirect(dataframecoolname) # must be the same name argument you used in the url
推荐阅读
- c++ - 如何将 OR-Tools 链接到我的 CMake 项目?
- visual-studio-code - 监视窗口中的 VSCode 调试器表达式未显示任何值
- android-studio - 如何添加必须使用插件和类路径的依赖项?
- azure-devops - 用于任务而非代理的 Devops 代理配置
- python - 如何在一定时间内停止 python 程序?
- swift - 限制列表的对象数量 - SwiftUi
- docker - Docker nginx 映像无法读取位于 docker 卷中的文件
- r - 如何将预先指定的随机变化引入R中的连续变量?
- xcode - 我的搜索栏中的文本字段不允许输入文本(swiftUI)
- python - 如何删除第一列和第三列中包含 NaN 的行?