How to show a PDF file in a Django view?

Django has a class specifically for returning files, FileResponse. It streams files, so that you don’t have to read the entire file into memory before returning it. Here you go:

from django.http import FileResponse, Http404

def pdf_view(request):
    try:
        return FileResponse(open('foobar.pdf', 'rb'), content_type="application/pdf")
    except FileNotFoundError:
        raise Http404()

If you have really large files or if you’re doing this a lot, a better option would probably be to serve these files outside of Django using normal server configuration.

Leave a Comment