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

Django中如何提取筛选后物品关联的season_support值用于PDF打印

Django 生成筛选后物品PDF的views.py实现

前置依赖安装

执行命令安装PDF转换工具:
pip install xhtml2pdf

views.py 完整代码

from django.shortcuts import render
from django.http import HttpResponse
from .models import Items
from xhtml2pdf import pisa

def generate_item_pdf(request):
    # 从请求参数获取筛选条件,无参数时配置默认值避免查询报错
    batch = request.GET.get('batch', '1000')
    area = request.GET.get('area', 'A01')
    
    # 按batch和area筛选Items表数据,仅查询需要的字段减少性能开销
    items = Items.objects.filter(batch=batch, area=area).only('id', 'item_name', 'season_support')
    
    # 渲染HTML模板
    template_path = 'index.html'
    context = {'items': items}
    response = HttpResponse(content_type='application/pdf')
    # 配置响应头:attachment强制触发下载,inline可直接在浏览器预览PDF
    response['Content-Disposition'] = 'attachment; filename="items_season_report.pdf"'

    # 将渲染后的HTML转换为PDF格式
    html = render(request, template_path, context).content
    pisa_status = pisa.CreatePDF(html, dest=response)
    
    # 处理PDF转换异常
    if pisa_status.err:
        return HttpResponse('PDF生成失败:%s' % pisa_status.err, status=400)
    return response

仅输出season_support字段的补充说明

如果不需要展示物品ID和名称,仅保留季节支持字段,直接修改index.html模板的循环部分即可,无需调整视图逻辑:

{% for item in items %}
<table>
    <tr>
       <td>Season support - {{ item.season_support }} </td>
    </tr>
</table>
{% endfor %}

内容的提问来源于stack exchange,提问作者VEERA BABU

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:18:04