You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Django-filter筛选结果转为PDF?xhtml2pdf使用报错求助

解决Django-filter筛选数据后用xhtml2pdf导出PDF的AttributeError问题

错误原因分析

你的代码存在两个核心问题:

  1. 注释掉了上下文定义context={'user':user},后续调用template.render(context)时,context变量未定义;且render_to_pdf返回的是渲染后的HTML字符串,并非可调用render方法的模板对象,对字符串调用render会触发类型错误。
  2. 模板中引用的{{ user }}无法从字符串对象中获取数据,直接导致'str' object has no attribute 'user'错误。

修正后的代码

from django.template.loader import render_to_string
from xhtml2pdf import pisa
from django.http import HttpResponse

def pdfview(request):
    # 初始查询集
    user_queryset = User.objects.all()
    # 应用Django-filter筛选
    gov_filter = GovFilter(request.GET, queryset=user_queryset)
    filtered_users = gov_filter.qs

    # 准备模板上下文,传递筛选后的数据
    context = {'users': filtered_users}
    # 将模板渲染为HTML字符串
    html_content = render_to_string('staff/pdf_template.html', context)

    # 构建PDF响应
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="report.pdf"'
    
    # 生成PDF并写入响应
    pisa.CreatePDF(html_content, dest=response)

    return response

额外注意事项

  • 模板staff/pdf_template.html中需遍历查询集数据(filtered_users是QuerySet对象),示例模板代码:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>用户报告</title>
</head>
<body>
    <h1>用户列表</h1>
    <table>
        <tr>
            <th>用户名</th>
            <th>邮箱</th>
        </tr>
        {% for user in users %}
        <tr>
            <td>{{ user.username }}</td>
            <td>{{ user.email }}</td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>
  • 确保已正确安装依赖:pip install xhtml2pdf django-filter

内容的提问来源于stack exchange,提问作者Raji Muhammad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 19:47:21