I've created a PDF Creator with WeasyPrint and included the download function. Is it now possible to store that PDF File immediately into a Model-FileField (called Invoice)? How should this code look like?
def generate_pdf(request):
# Rendered
html_string = render_to_string('bills/pdf/invoice.html', context)
html = HTML(string=html_string, base_url=request.build_absolute_uri())
result = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/bills.css')], presentational_hints=True);
# Creating http response
response = HttpResponse(content_type='application/pdf;')
invoice_number = context['invoice_id']
filename = "Invoice" + str(invoice_number) + ".pdf"
response['Content-Disposition'] = 'inline; filename="{}"'.format(filename)
pdf_file = HTML(string=html_string,
base_url=settings.MEDIA_ROOT).write_pdf()
new_bill = Invoice(invoice_no=billNumber, invoice_file=temp)
new_bill.save()
response['Content-Transfer-Encoding'] = 'binary'
with tempfile.NamedTemporaryFile(delete=True) as output:
output.write(result)
output.flush()
output = open(output.name, 'rb')
response.write(output.read())
download = request.GET.get("download")
if download:
content = "attachment; filename='%s'" %(filename)
response['Content-Disposition'] = output
return response
Here is a complete example from Django documentation, to access instance information in your models to build path with user id :
models.py