Django:“initial_value必须是str或None,而不是字节”错误

时间:2018-02-27 11:56:17

标签: python django pdf

在学习Django和Python时,我正在尝试下载pdf文件。文件内容应来自html模板。我正在尝试使用pisaDocument示例(并且来自互联网的任何其他示例都是相同的)。在我的情况下,我在initial_value must be str or None, not bytes部分收到StringIO(html.encode("utf-8"))错误。我明白问题是StringIo需要一个str而且它返回字节,但我怎样才能将字节转换为str?

from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect
from django.template.loader import get_template
from django.views.decorators.csrf import csrf_exempt
from io import StringIO, BytesIO
from cgi import escape

def export(request):
    if(request.POST):
        client = request.POST.get('client')
        doc = request.POST.get('doc')
        template = get_template('files/insurance.html.twig')
        html = template.render()
        result = StringIO(html)

        pdf = pisa.pisaDocument(StringIO(html.encode("utf-8")), result)
        if not pdf.err:
            return HttpResponse(result.getvalue(), content_type='application/pdf')
        return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
    else:
        raise Http404("POST data not found")

0 个答案:

没有答案