Создать Скачать PDF файл и сохранить его в модель - PullRequest
0 голосов
/ 17 ноября 2018

Я создал PDF Creator с WeasyPrint и включил функцию загрузки.Теперь можно ли сохранить этот 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

1 Ответ

0 голосов
/ 17 ноября 2018

Вот полный пример из документации Django для доступа к информации об экземплярах в ваших моделях для построения пути с идентификатором пользователя:

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)
...