创建下载PDF文件并将其存储到模型中

时间:2018-11-17 14:03:18

标签: python django model weasyprint

我已经用WeasyPrint创建了PDF Creator,并包含了下载功能。现在是否可以立即将PDF文件存储到Model-FileField(称为发票)中?该代码应如何显示?

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

1 个答案:

答案 0 :(得分:0)

这是Django文档中的完整示例,用于访问模型中的实例信息以使用用户ID构建路径:

models.py

def user_directory_path(instance, filename):
        # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
        return 'user_{0}/{1}'.format(instance.user.id, filename)

    class YourClass(models.Model):
    invoice = models.FileField(default='default.pdf', upload_to=user_directory_path)