首页 > 解决方案 > Django将多个实例的HttpResponse转换为PDF并压缩它们不起作用

问题描述

我正在尝试从查询集中获取多个实例,然后对于每个实例,使用xhtml2pdf包从 HttpResponse 对象创建一个 PDF,然后最终压缩所有生成的 PDFS 以供下载。

这是我到目前为止所拥有的:

def bulk_cover_letter(request, ward_id, school_cat_id):
    report_files = {}
    school_type = SchoolType.objects.get(id=school_cat_id)
    ward = Ward.objects.get(id=ward_id)

    schools_in_school_type = Applicant.objects.filter(
     school_type=school_type, ward_id=ward_id, award_status='awarded').order_by().values_list(
     'school_name', flat=True).distinct()

    for school in schools_in_school_type:
        cheque_number = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school).values_list('cheque_number__cheque_number', flat=True).distinct()
        beneficiaries = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school)
        total_amount_to_beneficiaries = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school).aggregate(total=Sum('school_type__amount_allocated'))

        context = {
            'school_name' : school,
            'beneficiaries' : beneficiaries,
            'total_amount_to_beneficiaries' : total_amount_to_beneficiaries,
            'title' : school + ' Disbursement Details',
            'cheque_number': cheque_number[0]
        }

        response = HttpResponse('<title>Cover Letter</title>', content_type='application/pdf')
        filename = "%s.pdf" %(cheque_number[0])
        content = "inline; filename=%s" %(filename)
        response['Content-Disposition'] = content
        template = get_template('cover_letter.html')
        html = template.render(context)

        mem_fp = io.BytesIO()
        pdf = pisa.CreatePDF(
            html, dest=mem_fp, link_callback=link_callback)
        resp = HttpResponse(mem_fp.getvalue(), content_type='application/pdf')
        resp['Content-Disposition'] = "attachment; filename=%s" %(filename)
        report_files[filename] = resp

    mem_zip = io.BytesIO()
    with zipfile.ZipFile(mem_zip, mode="w") as zf:
        for filename, content in report_files.items():
            zf.writestr(filename, content)
    response = HttpResponse(mem_zip, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename="{}"'.format(f'{ward}_cover_letters.zip')

    return response    

一切正常,直到拉链部分。我收到错误:

'HttpResponse' 类型的对象没有 len()

我该怎么做?

标签: pythondjangozipxhtml2pdf

解决方案


推荐阅读