Automaticaly downloadable invoice pdf
I want to create an option to download a pdf file having an invoice with the following properties in the django database admin:
models.py:
from django.db import models
from appsystem.models import Outlet
from core.models import Item, Supplier
from location.models import Warehouse, Zone, Section, Level
class MainPurchases(models.Model):
METHOD_A = 'CASH'
METHOD_B = 'CREDIT'
PAYMENT_METHODS = [
(METHOD_A, 'CASH'),
(METHOD_B, 'CREDIT'),
]
product = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.PositiveSmallIntegerField()
purchase_price = models.DecimalField(max_digits=6, decimal_places=2)
paid_amount = models.DecimalField(max_digits=6, decimal_places=2)
date_created = models.DateTimeField(auto_now_add=True)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
I need this to be a printable invoice slip with the specified values but I just can't get anywhere.
It's really two questions. How to generate pdf from data in the DB, and how to deliver it to a web client (browser).
In answer to the second, here's a view I wrote earlier
from io import BytesIO
def pdfview( request, pk):
quote = get_object_or_404( Quote, pk=pk) # object to build pdf from
pdf = build_pdf( quote)
iobuf = BytesIO( bytearray(pdf.output( dest='S' ), encoding='latin-1'))
response = HttpResponse( iobuf, content_type='application/pdf')
response['Content-Disposition'
] = 'inline; filename={}.pdf'.format(quote.quotenumber)
# inline; will ask for an immediate display of the content
# attachment; will offer options to the user, including save without display
# exact details are browser-specific.
return response
As for build_pdf, I was using fpdf
from fpdf import FPDF
def build_pdf( quote):
pdf = FPDF()
# pdf.this( ...)
# pdf.that( ...)
# much later, when done
return pdf