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

Question:

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.

Asked By: coffee-and-code

||

Answers:

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>
Answered By: luke jon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.