django:触发下载后重定向到另一个页面

时间:2019-07-09 04:06:39

标签: 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')

1 个答案:

答案 0 :(得分:0)

您可以为您提到的数据框创建一个视图,将该视图注册到urls.py文件中,并且在发生某些情况后可以在redirect方法中使用此新视图,例如在使用后,单击下载按钮重定向到数据框并开始下载,或者下载可能已在最后一个视图中开始。

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