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