Django 输出 pdf

the*_*ame 2 django view

大家好,因为我在 Django 的学习阶段,所以支持我。我必须在 django 中生成 pdf 报告。我希望应该从数据库中选择详细信息并显示在 pdf 文档中。我正在使用报告实验室。现在看看代码

def pdf_view(request):
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=hello.pdf'
    p = canvas.Canvas(response)
    details = Data.objects.all()
    print details

    p.drawString(20, 800, details)
    p.drawString(30, 700, "I am a Python Django Professional.")
    p.showPage()
    p.save()
    return response
Run Code Online (Sandbox Code Playgroud)

现在作为学习示例,我在模型中创建了两个字段

class Data(models.Model):
    first_name = models.CharField(max_length =100,blank=True,null=True)
    last_name = models.CharField(max_length =100,blank=True,null=True)

    def __unicode__(self):
        return self.first_name
Run Code Online (Sandbox Code Playgroud)

我希望在 pdf 文档中它应该显示我通过管理员填写的任何名称,但它给了我错误

'Data' object has no attribute 'decode'

Request Method:     GET
Request URL:    http://localhost:8000/view_pdf/
Django Version:     1.3
Exception Type:     AttributeError
Exception Value: 
Run Code Online (Sandbox Code Playgroud)

我想从数据库中提取详细信息并显示在 pdf 文档中

'Data' object has no attribute 'decode'
Run Code Online (Sandbox Code Playgroud)

Dan*_*man 5

如果您发布了实际的回溯,它会有所帮助。

但是我希望问题是这一行:

p.drawString(20, 800, details)
Run Code Online (Sandbox Code Playgroud)

Details 是一个查询集,它是一个类似列表的模型实例容器。它不是字符串,也不包含字符串。也许你想要这样的东西:

detail_string = u", ".join(unicode(obj) for obj in details) 
Run Code Online (Sandbox Code Playgroud)

它在查询__unicode__集中的每个对象上调用该方法,并用逗号连接结果列表。