首页 > 解决方案 > 通过电子邮件发送从 HTML 生成的 PDF:预期的类似字节的对象,而不是 HttpResponse

问题描述

我正在尝试通过电子邮件发送从 HTML 模板生成的 PDF。

我收到以下错误:expected bytes-like object, not HttpResponse

generate_pdf

def generate_pdf(template_src, context_dict={}):
   template = get_template(template_src)
   html  = template.render(context_dict)
   result = BytesIO()
   pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
   if not pdf.err:
       return HttpResponse(result.getvalue(), content_type='application/pdf')
   return None

view for pdf emailing

def pdfView(request):

   data = {'test':'test',
              'mylist': 'test'
              }
   pdf = generate_pdf('main/test.html', data)
   msg = EmailMessage("title", "content", to=["email@email.com"])
   msg.attach('my_pdf.pdf', pdf, 'application/pdf')
   msg.content_subtype = "html"
   msg.send()

   return HttpResponse(pdf, content_type='application/pdf')

标签: pythondjango

解决方案


HttpResponse在函数中返回 a 。

简单地改变return HttpResponse(result.getvalue(), content_type='application/pdf')

return result.getvalue()


推荐阅读