Downloading a file in Django

Creating a view in Django to download a certain file is pretty easy. Actually the HttpResponse object will do a lot of works for us, and the only thing we need to do is to tell django what is the type of your file which will be returned:

For example, I want to create a view which help user download a pdf file:

from django.http import HttpResponse

def download_pdf(request):
    pdf_file = open('/path/to/pdffile.pdf', 'r')
    response = HttpResponse(pdf_file, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=mypdf.pdf'

    return response

The content_type parameter is the mimetype of your file.