In one of the previous article, we learned how to generate and return the PDF file in response. This was the right choice if you want to download the PDF file. But if you want to display PDF file inside the browser window then we need to make use of FileResponse.
Remember that browsers won't display PDF if proper plugins are not available.
Let's say you want to display the payslip of employees. Below is the directory structure where we are going to store the payslips.
-project |-media | |-payslips | | |-2019 | | | |-january | | | |-feburary | | | | |-6754599.pdf | | | | |-6754600.pdf
All the media files are stored in the media
folder in the project root. We have further created more folders to segregate documents. Salary slips are stored year and month wise. Salary slip file name is [employee id].[extension], pdf in this case.
Now in view responsible to display payslip, write below code.
@login_required
def payslip_view(request, employee):
data = dict()
data["employee"] = employee
if "GET" == request.method:
return render(request, "appname/payslip.html", data)
# else for post call, procced
post_data = request.POST.copy()
year = post_data.get("year", None)
month = post_data.get("month", None)
if not year or not month:
messages.error(request, "Please select year and month.")
return HttpResponseRedirect(reverse("appname:payslip", args=(employee,)))
try:
filename = employee + ".pdf"
filepath = os.path.join(settings.MEDIA_ROOT, "payslips", year, month, filename)
print(filepath)
return FileResponse(open(filepath, 'rb'), content_type='application/pdf')
except FileNotFoundError:
messages.error(request, "Payslip of Employee with Id " + employee + " doesn't exists for " + month + " " + year)
return HttpResponseRedirect(reverse("appname:payslip", args=(employee,)))
Import required classes/modules.
from django.contrib import messages
from django.http import HttpResponseRedirect, Http404, FileResponse
from django.shortcuts import render
from django.urls import reversefrom django.contrib.auth.decorators import login_required import os from django.conf import settings
You need to create another view which will display the HTML page with drop downs to select year and month for the logged in employee. Once the year and month are selected and form is submitted, post request is handled by the above view and payslip is displayed in the browser window.