0

我用 Wea​​syPrint 创建了一个 PDF Creator 并包含了下载功能。现在是否可以将该 PDF 文件立即存储到 Model-FileField(称为 Invoice)中?这段代码应该是什么样子?

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
4

1 回答 1

0

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

模型.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)
于 2018-11-17T14:39:10.397 回答