我正在尝试在django中循环用户数据,以便在reportlab的帮助下创建一个表。但是我遇到了一个attributeError,它的'tuple‘对象没有'username’属性。
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非常感谢!
发布于 2018-01-18 01:35:50
values_list返回一个元组列表,这些元组不支持点引用。你想要像username = i[0].encode('utf-8')这样的东西,或者使用values来获取字典,然后使用i['username'].encode('utf-8')。或者使用User.objects.all().only('username', 'email') -这将提供模型实例,将这些字段加载到内存中,并延迟所有其他字段,这将支持点引用。
为了清楚起见,我使用values() -它比使用values_list更容易知道发生了什么,而模型实例比您需要的更重,并且可以隐藏进行额外查询或更新初始查询集的需要(如果您确实开始需要更多字段)。
https://stackoverflow.com/questions/48306246
复制相似问题