51👍
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.
37👍
Simplistically, if you have a PDF file and you want to output it through a Django view, all you need to do is dump the file contents into the response and send it with the appropriate mimetype.
def pdf_view(request):
with open('/path/to/my/file.pdf', 'r') as pdf:
response = HttpResponse(pdf.read(), mimetype='application/pdf')
response['Content-Disposition'] = 'inline;filename=some_file.pdf'
return response
pdf.closed
You can probably just return the response directly without specifying Content-Disposition, but that better indicates your intention and also allows you specify the filename just in case the user decides to save it.
Also, note that the view above doesn’t handle the scenario where the file cannot be opened or read for whatever reason. Since it’s done with with
, it won’t raise any exceptions, but you still must return some sort of response. You could simply raise an Http404
or something, though.
- [Django]-Django : Is it impossible to static tag into block tag?
- [Django]-Os.getcwd() vs os.path.abspath(os.path.dirname(__file__))
- [Django]-Foreignkey (user) in models
16👍
PDF files must be opened as rb
not r
.
def pdf_view(request):
with open('/path / to /name.pdf', 'rb') as pdf:
response = HttpResponse(pdf.read(),content_type='application/pdf')
response['Content-Disposition'] = 'filename=some_file.pdf'
return response
- [Django]-Django reverse lookup of foreign keys
- [Django]-Where can I find the error logs of nginx, using FastCGI and Django?
- [Django]-How do I execute raw SQL in a django migration
8👍
Take out inline; if you want your file to be read from server. And also, the HttpResponse
kwarg mimetype
has been replaced by content_type
:
(response['Content-Disposition'] = 'inline;filename=some_file.pdf')
def pdf_view(request):
with open('/app/../Test.pdf', 'r') as pdf:
response = HttpResponse(pdf.read(),content_type='application/pdf')
response['Content-Disposition'] = 'filename=some_file.pdf'
return response
pdf.closed
- [Django]-Tool for pinpointing circular imports in Python/Django?
- [Django]-How to run gunicorn from a folder that is not the django project folder
- [Django]-How do you convert a PIL `Image` to a Django `File`?
8👍
Following @radtek’s answer above I decided to investigate a class-based view display. I tried to use View
but it didn’t have get_context_data()
method.
I looked here for some guidance. I settled for BaseDetailView
since I wanted to display just one object.
from django.http import FileResponse
from django.shortcuts import get_object_or_404
from django.views.generic.detail import BaseDetailView
class DisplayPdfView(BaseDetailView):
def get(self, request, *args, **kwargs):
objkey = self.kwargs.get('pk', None) #1
pdf = get_object_or_404(Pdf, pk=objkey) #2
fname = pdf.filename() #3
path = os.path.join(settings.MEDIA_ROOT, 'docs\\' + fname)#4
response = FileResponse(open(path, 'rb'), content_type="application/pdf")
response["Content-Disposition"] = "filename={}".format(fname)
return response
Commentary
1 This line accesses a named argument pk
passed by the url calling the view.
2 This line gets the actual pdf model object.
3 I defined a method filename(self): return os.path.basename(self.file.name)
in my model to help me get just the filename plus extension.
4 This line gets the complete filepath.
Then use file response as explained in the answers above. Also remember to use rb
to read the pdf file
- [Django]-Django Rest Framework, passing parameters with GET request, classed based views
- [Django]-How to reset migrations in Django 1.7
- [Django]-Catching DoesNotExist exception in a custom manager in Django
4👍
Here is a typical use-case for displaying a PDF using class-based views:
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
class DisplayPDFView(View):
def get_context_data(self, **kwargs): # Exec 1st
context = {}
# context logic here
return context
def get(self, request, *args, **kwargs):
context = self.get_context_data()
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'inline; filename="worksheet_pdf.pdf"' # Can use attachment or inline
# pdf generation logic here
# open an existing pdf or generate one using i.e. reportlab
return response
# Remove login_required if view open to public
display_pdf_view = login_required(DisplayPDFView.as_view())
For generating your own pdf with reportlab see the Django project Docs on PDF Generation.
Chris Pratt’s response shows a good example of opening existing PDFs.
- [Django]-Cannot apply DjangoModelPermissions on a view that does not have `.queryset` property or overrides the `.get_queryset()` method
- [Django]-How to update multiple fields of a django model instance?
- [Django]-How to duplicate virtualenv
0👍
Browsers aren’t PDF readers (unless they have the proper plugin/addon).
You may want to render the PDF as HTML instead, which can be done from the backend or the frontend.
- [Django]-Rendering a value as text instead of field inside a Django Form
- [Django]-Adding css class to field on validation error in django
- [Django]-How can I make a trailing slash optional on a Django Rest Framework SimpleRouter
0👍
it worked for me
import re, os
import os
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def export_auto_doc(request):
name = request.GET.get('name', "")
filename = "path/to/file"+name+".pdf"
try:
if not re.search("^[a-zA-Z0-9]+$",name):
raise ValueError("Filename wrong format")
elif not os.path.isfile(filename):
raise ValueError("Filename doesn't exist")
else:
with open(filename, 'r') as pdf:
response = HttpResponse(pdf.read(), content_type='application/pdf')
response['Content-Disposition'] = 'inline;filename='+name+'.pdf'
return response
pdf.closed
except ValueError as e:
HttpResponse(e.message)
- [Django]-Django: Purpose of django.utils.functional.SimpleLazyObject?
- [Django]-Django filter JSONField list of dicts
- [Django]-How do I perform query filtering in django templates
0👍
I am just throwing this out there.
You can simply add your PDF resume to your static files.
If you are using White Noise to serve your static files, then you don’t even need to make the view. Just then access your resume at the static location.
I added mine, here it is: TIm-D_Nice.pdf
Warning: This doesn’t solve the login_required
requirement in the question
- [Django]-Database returned an invalid value in QuerySet.dates()
- [Django]-How to override and extend basic Django admin templates?
- [Django]-How can I make a trailing slash optional on a Django Rest Framework SimpleRouter
0👍
The easiest way to do this is probably with an anchor in a template. For example, if you are using Django’s templating engine (as most people who search for this probably are), simply serve it as a static file through an anchor.
In your template that will contain a link to the file, add at the very top
{% load static %}
Then, wherever you want to link to your pdf, put
<a href="{% static 'relative/path/file.pdf' %}">Click me</a>
The first line tells Django to look in the directories configured for static files in settings.py
. The path that you use in the anchor tag is relative to any of the directories that you configured as static directories in settings.py
. When you click the rendered link, it should display the PDF in your browser, provided you have your static files pathed correctly.
- [Django]-Django: Overriding AND extending an app template
- [Django]-Sending post data from angularjs to django as JSON and not as raw content
- [Django]-Difference between django-redis-cache and django-redis for redis caching with Django?
0👍
Use iframe url=url of pdf tag and give url of that pdf and make sure that your user will have full control of the project then pdf will be displayed on web screen
- [Django]-Allowing RabbitMQ-Server Connections
- [Django]-What is the best django model field to use to represent a US dollar amount?
- [Django]-Django Rest Framework remove csrf
0👍
def pdf_view(request,pdfSlug):
a = Pdf.objects.get(pdf_slug=pdfSlug)
with open(str(a.pdf_file.path), 'rb') as pdf:
response = FileResponse(pdf.read(), content_type='application/pdf')
response['Content-Disposition'] = 'filename=a.pdf'
return response
pdf.closed
look this i’ts warked for me
- [Django]-What is the most efficient way to store a list in the Django models?
- [Django]-Django ignores router when running tests?
- [Django]-Adding REST to Django