这似乎是一个非常简单的问题,但我无法解决它:(
我有一个应该为我创建 pdf 文件的 View 。我需要一个循环,但我不知道为什么它不起作用。我需要打印列表中的所有问题。 我已经检查过,“pytanie”列表中有 3 个问题,但我的循环只打印一个问题(最后一个问题)
for i in range(len(pytanie)):
p = canvas.Canvas(response)
p.drawString(10, 800, ' '+ pytanie[i].title)
此 View 中的整个代码
from reportlab.pdfgen import canvas
from django.http import HttpResponse
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.barcode.qr import QrCodeWidget
from reportlab.graphics import renderPDF
from django.contrib.auth.models import User
from pytania.models import Pytanie
def test_qr(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="egzamin.pdf"'
pytanie = Pytanie.objects.all()
for i in range(len(pytanie)):
p = canvas.Canvas(response)
p.drawString(10, 800, ' '+ pytanie[i].title)
qrw = QrCodeWidget('a')
b = qrw.getBounds()
w=b[2]-b[0]
h=b[3]-b[1]
d = Drawing(200,200,transform=[200./w,0,0,200./h,0,0])
d.add(qrw)
renderPDF.draw(d, p, 1, 1)
p.showPage()
p.save()
return response
最佳答案
- 你应该只循环 Pytanie.objects.all():
将p的初始化放在循环之外
p = canvas.Canvas(response) for pytanie in Pytanie.objects.all(): p.drawString(10, 800, ' '+ pytanie.title)
关于python - django View 中的简单 for 循环创建 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28252566/