简体   繁体   中英

How can I return a redirect and file in Django?

I'm working on a form that when submitted has the option to export a PDF. This is great, but I would also like to be able to return a new URL for the user to be redirected to as well as downloading the file. Something that combines render() or redirect() with FileResponse() .

For this to work, you will need two views. One to serve the redirect and another one to serve the file to be downloaded. Here is a simplified implementation:

def myform(request):
    form = MyForm(request.POST)
    if form.is_valid():
        return redirect("/download/file.pdf")

def download(request):
    file = open("file.pdf", "rb")
    return FileResponse(file, as_attachment=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM