在渲染 pdf 和使用 pdfkit 和 Django 填充 table 之前循环遍历项目

Loop through items before rendering pdf and populating table using pdfkit and Django

我正在尝试在呈现的 pdf 中导出我的所有用户和与他们相关的数据。我正在努力遍历所有用户并为每个用户创建新的 table 行。按照现在的循环遍历所有用户,但它只用最后一个注册用户的数据填充 table。

我认为我无法使用 Django 的传统循环方式,至少我不知道如何将上下文传递给模板。

views.py

def users_export(request):
    users = User.objects.all()

    # Populate template tags in generated pdf with data
    data = dict()
    for user in users:
        data['full_name'] = user.get_full_name

    # Getting template, and rendering data
    template = get_template('backend/users/users_export.html')
    html = template.render(data)
    pdf = pdfkit.from_string(html, False)

    # Function for creating file name
    # Inner function
    def create_file_name():
        file_name = 'users %s.pdf' % (timezone.now())
        return file_name.strip()

    filename = create_file_name()

    response = HttpResponse(pdf, content_type = 'application/pdf')
    response['Content-Disposition'] = 'attachment; filename="' + filename + '"'
    
    return response

users_export.html

<table>
   <tr class="thead">
       <th class="text-left">Name</th>
   </tr>
   <tr>
       <td class="text-left">{{ full_name }}</td>
   </tr>
</table>

您正确地循环了用户,但以错误的方式将其保存在字典中。 您每次都在覆盖 full_name 键。您应该使用用户的唯一值作为键,全名作为值

data = dict()

for user in users:
   user[user.username] = user.full_name

此外,我不知道 pdfkit,但假设它类似于 Jinja 或 django 模板,您将需要遍历所有项目。

另一种选择是简单地传递全名列表而不是字典

data = [user.full_name for user in users]

编辑:

生成您还需要更改模板以及将数据传递给渲染函数的方式。

试试这个:

html = template.render({"users": data})

模板



<table>
   <tr class="thead">
       <th class="text-left">Name</th>
   </tr>
   {% for user in users %} // this is assuming that you are using the list
   <tr>
       <td class="text-left">{{ user }}</td>
   </tr>
   {% endfor %}
</table>