首页 > 解决方案 > 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')

标签: pythondjango

解决方案


您可以为您提到的数据框创建一个视图,在 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

推荐阅读