Python 使用reportlab创建表
我试图在reportlab的帮助下循环django中的用户数据以创建一个表。但我遇到了一个attributeError,“tuple”对象没有属性“username”Python 使用reportlab创建表,python,django,reportlab,Python,Django,Reportlab,我试图在reportlab的帮助下循环django中的用户数据以创建一个表。但我遇到了一个attributeError,“tuple”对象没有属性“username” def admin_tools_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="users.pdf" ' buffer
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
非常感谢
values\u list
返回不支持点解引用的元组列表。您需要类似于username=i[0]。编码('utf-8')
,或者使用value
来获取dict,然后使用i['username']。编码('utf-8')
。或者使用User.objects.all()。only('username','email')
-这将为您提供模型实例,其中这些字段加载到内存中,所有其他字段延迟,这将支持点引用
为了清晰起见,我会使用
values()
,这比使用values\u list
更容易判断发生了什么,虽然模型实例比您需要的更重,并且如果您确实开始需要更多字段,可以隐藏进行额外查询或更新初始查询集的需要。您可以提供错误的完整日志吗?我修复了这个问题,但现在我得到一个类型错误:关于此行的非序列迭代,table=table(数据,冷宽=[4*cm,4*cm,4*cm,4*cm])
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