Vaios Lk Vaios Lk - 25 days ago 14
Python Question

Downloading file from FileField in Django with a HTTP link in a HTML file

I create a link that when a user press it, it will download a pdf file from the media folder in Django to the users machine.

I tried different methods but all were wrong for me. It tells me that the file can not be found, or the code is running but the file is corrupted.

My Html link:

<td> <a href="/download/">Download</a></td>


My url pattern links into a view:

url(r'^download/$', views.DownloadPdf),


My FileField is like this:

upload_pdf = models.FileField()


Following snippet code is the view that downloads a corrupted pdf:

def DownloadPdf(request):

filename = '/home/USER/PycharmProjects/MyProject/media/Invoice_Template.pdf'
response = HttpResponse(content_type='application/pdf')
fileformat = "pdf"
response['Content-Disposition'] = 'attachment;
filename=thisismypdf'.format(fileformat)
return response


So, what I have to do to make it working ?

Answer
with open(os.path.join(settings.MEDIA_ROOT, 'Invoice_Template.pdf'), 'rb') as fh:
    response = HttpResponse(fh.read(), content_type="application/pdf")
    response['Content-Disposition'] = 'attachment; filename=invoice.pdf'
    return response
Comments