python - 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()
我该怎么做?
解决方案
推荐阅读
- android - xml下方不明空间空间
- javascript - 构建后使用外部 Vue 组件
- matlab - MATLAB:nx1 Char 的“ismember”函数
- android - 如何获取 FloatingActionButton 的当前颜色
- python - Heroku 减少 TensorFlow 应用程序的内存消耗
- javascript - 类型错误:无法读取 undefined-Discord.js 的属性“内容”
- esp8266 - esp8266 - 如何在 spi 上写入代码段?
- python - 如何绘制不同颜色的线
- python - 2 一次变换的数据帧乘法
- angular - 使用 rxjs 在 Angular 中转换 http 服务响应