【问题标题】:Working with reportlab to create tables使用 reportlab 创建表格
【发布时间】:2018-01-18 23:22:19
【问题描述】:

我正在尝试在 django 中循环用户数据以在 reportlab 的帮助下创建一个表。但是我遇到了一个属性错误,即“元组”对象没有属性“用户名”。

def admin_tools_pdf(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment;   filename="users.pdf" '  
buffer=BytesIO()
p=canvas.Canvas(buffer,pagesize=A4)
width, height = A4
styles = getSampleStyleSheet()
styleN = styles["BodyText"]
styleN.alignment = TA_LEFT
styleBH = styles["Normal"]
styleBH.alignment = TA_CENTER
user_data=User.objects.all().values_list('username','email')
username=Paragraph("'<b>Username</b>'",styleBH)
email=Paragraph("'<b>Email Id</b>'",styleBH)
data=[[username,email]]
for i in user_data:
    username=str(i.username).encode('utf-8')
    email=str(i.email).encode('utf-8')
    user=Paragraph(username,styleN)
    mail=Paragraph(email,styleN)
    data+=[user,mail]
table=Table(data,colWidths=[4*cm,4*cm,4*cm,4*cm])
table.wrapOn(p, width, height)
table.wrapOn(p, width, height)
table.drawOn(p)
p.showpage()
p.save()
pdf=buffer.getvalue()
buffer.close()
response.write(pdf)
return response

导入文件为:

from io import BytesIO
from reportlab.pdfgen import canvas

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle,Paragraph
from reportlab.lib.pagesizes import A4, cm 
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER

非常感谢!

【问题讨论】:

  • 你能提供你的完整日志吗

标签: python django reportlab


【解决方案1】:

values_list 返回不支持点解引用的元组列表。你想要username = i[0].encode('utf-8') 之类的东西,或者使用values 来获取字典并使用i['username'].encode('utf-8')。或者使用User.objects.all().only('username', 'email') - 这将为您提供模型实例,其中这些字段加载到内存中,所有其他字段都被延迟,这将支持点引用。

为了清楚起见,我会使用 values() - 它比使用 values_list 更容易判断发生了什么,而模型实例比您需要的更重,并且可以隐藏进行额外查询或更新初始查询集的需要,如果您确实开始需要更多字段。

【讨论】:

  • 我修复了这个问题,但现在我得到了一个 TypeError: 在非序列上迭代关于这一行,table=Table(data,colWidths=[4*cm,4*cm,4*cm ,4*cm])
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
相关资源
最近更新 更多