Report Lab 从表单而不是数据库打印值

Report Lab Printing Values From Forms Rather Than Database

我有一个网站,用户必须在该网站上完成分布在四个网页(和四个表格)中的大型调查问卷,完成调查问卷后,reportlab 会生成他们答案的 pdf 文件。

这是我的工作代码

utils.py

def generate_pdf(request):
    # get user
    user = request.user

    # get users age
    born = request.user.personalinformation.dob
    age = user_utils.get_age(born)

    doc = SimpleDocTemplate(settings.MEDIA_ROOT+'\pdf_templates\enrolment_form_%s.pdf' %user.id)
    styles = getSampleStyleSheet()
    enrolment_form = [Spacer(1,2*inch)]
    style = styles["Normal"]

    page_contents = [
    ("Name: %s %s" % (user.personalinformation.first_name, user.personalinformation.surname)),
    ("Gender: %s" % (user.personalinformation.gender)),
    ("Age: %s" % (age))
    ]

    for sections in page_contents:
        p = Paragraph(sections, style)
        enrolment_form.append(p)
        enrolment_form.append(Spacer(1,0.2*inch))

    doc.build(enrolment_form)

models.py

class PersonalInformation(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    GENDERS = (
        ('M', 'Male'),
        ('F', 'Female'),
    )

    first_name = models.CharField(max_length=200, default='')
    surname = models.CharField(max_length=200, default='')
    gender = models.CharField(max_length=1, choices=GENDERS)
    dob = models.DateTimeField('Date of birth (mm/dd/yyyy)', null=True, default=now)

    def __str__(self):
        return f'{self.user.username}'

(我也有一个 form.py 但不认为它值得包括)

除了像 'gender' 这样的字段,这工作正常。因为它从数据库的 user.personalinformation 获取它在 pdf 上打印的值,而不是打印 'Gender: Male',它打印 'Gender: M'。虽然这个例子看起来微不足道,但还有更多字段包含 key/value 对和布尔值,以这种方式打印毫无意义。

如何打印表单中显示给用户的值,而不是打印保存在数据库中的值?

谢谢。

field.choices documentation开始

For each model field that has choices set, Django will add a method to retrieve the human-readable name for the field’s current value. See get_FOO_display() in the database API documentation.

因此您必须使用 get_FOO_display() 函数来获取记录的值

user.personalinformation.get_gender_display()