Categories
Python Answers

How to show a PDF file in a Python Django view?

Spread the love

Sometimes, we want to show a PDF file in a Python Django view.

In this article, we’ll look at how to show a PDF file in a Python Django view.

How to show a PDF file in a Python Django view?

To show a PDF file in a Python Django view, we can create a FileResponse and return it.

For instance, we write

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()

to create the pdf_view view that returns the FileResponse object that we create by opening the foobar.pdf PDF file.

We set the content_type argument to 'application/pdf' to make the client know that the file is a PDF.

If the file isn’t found, then we return a 404 response with Http404.

Conclusion

To show a PDF file in a Python Django view, we can create a FileResponse and return it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *