Home > OS >  Downloading a file from Django template on click doesn't work
Downloading a file from Django template on click doesn't work

Time:10-13

I tried multiple ways to download a file on click from a Django template, but the download just won't start. Here's my view where I get the file path:

def success(request):
    model_file_path = request.session.get('model_file_path')
    if request.method == 'POST':
        return render(request, "success.html", {'filepath': model_file_path})
    else:
        return render(request, "success.html", {'filepath': model_file_path})

And here is what I tried in the success template with no success:

 <a href='{{filepath}}' download>download</a>
 <a href='{{ MEDIA_URL }}{{filepath}}' download={{filepath}}>download</a>
 <a href='{{filepath}}' download={{filepath}}>download</a>

It just won't trigger a download, although the path is correct.

CodePudding user response:

You should use FileResponse from django.http from django.http import FileResponse.

...

    return FileResponse(open(model_file_path, 'rb'), as_attachment=True)
else:
    return FileResponse(open(model_file_path, 'rb'), as_attachment=True)

Edit:

def success(request):
    model_file_path = request.session.get('model_file_path')
    if request.method == 'POST':
        return render(request, 'success.html')
    else:
        return FileResponse(open(model_file_path, 'rb'), as_attachment=True)

<a href='{{ MEDIA_URL }}{{filepath}}' download={{filepath}}>download</a>
  • Related