[Answered ]-Downloading file from FileField in Django with a HTTP link in a HTML file

1👍

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

1👍

@Sergey Gornostaev ‘s code just work perfect, but i post below my code because it is a aproach in a differect way.

I correct a little bit my code:

def DownloadPdf(request):
    path_to_file = '/home/USER/PycharmProjects/MyProject/media /Invoice_Template.pdf'
    f = open(path_to_file, 'r')
    myfile = File(f)
    response = HttpResponse(myfile, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=filename'
    return response

But only in pdf file ( works with txt files ) gives me that error:

‘utf-8’ codec can’t decode byte 0xe2 in position 10

Leave a comment