大家好,我正处于 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
现在作为学习示例,我在模型中创建了两个字段
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
我希望在 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:
我想从数据库中获取详细信息并显示在pdf文档中
'Data' object has no attribute 'decode'
最佳答案
如果您发布了实际的回溯,将会有所帮助。
但是我预计问题出在这一行:
p.drawString(20, 800, details)
Details 是一个查询集,它是模型实例的类似列表的容器。它不是字符串,也不包含字符串。也许你想要这样的东西:
detail_string = u", ".join(unicode(obj) for obj in details)
它对查询集中的每个对象调用 __unicode__
方法,并用逗号连接结果列表。
关于Django 输出 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6423638/