[Python] Working with reportlab to create tables

Discussão em 'Python' iniciado por Stack, Agosto 24, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to loop the user data in django to create a table with the help of reportlab. But I am running into an attributeError that 'tuple' object has no attribute '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


    The import files are:

    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


    Thanks a lot!

    Continue reading...

Compartilhe esta Página