
本文详解如何在Odoo自定义向导(TransientModel)中正确生成并响应式下载CSV文件,重点解决因缺失binary字段导致的“field not found”错误,并提供安全、健壮、可复用的代码实现。
本文详解如何在odoo自定义向导(transientmodel)中正确生成并响应式下载csv文件,重点解决因缺失`binary`字段导致的“field not found”错误,并提供安全、健壮、可复用的代码实现。
在Odoo中通过向导(Wizard)导出CSV文件是常见需求,但直接使用ir.actions.act_url配合web/content/路由时,若未正确定义并填充binary字段,系统会抛出类似'file' field not found的错误(如截图所示)。根本原因在于:web/content/?model=...&field=file 路由要求模型中必须存在名为 file 的 fields.Binary 字段,且该字段需在动作触发前被赋值为Base64编码的文件内容。
以下是修正后的完整、生产就绪实现方案:
✅ 正确步骤与关键修改点
-
添加 file 二进制字段(必需)
在向导模型中声明一个 fields.Binary 字段,用于临时存储CSV内容(Odoo会自动处理其存储与清理):
from odoo import models, fields, api
import csv
import io
import base64
from odoo.exceptions import UserError
class ReportPatientWizard(models.TransientModel):
_name = "report.patient.wizard"
_description = "Patient Reports"
patient_id = fields.Many2one('hospital.patient', string='Patient', readonly=True)
gender_filter = fields.Selection([
('male', 'Male'),
('female', 'Female'),
('other', 'Other')
], string='Gender Filter')
# ? 新增:用于存储导出文件的Binary字段(必需!)
file = fields.Binary(string="Download File", readonly=True, attachment=True)
filename = fields.Char(string="File Name", readonly=True) # 可选,提升用户体验-
修正导出逻辑:编码 + 赋值 + 返回动作
- 使用 self.ensure_one() 确保单记录上下文;
- CSV内容需以UTF-8编码后经 base64.b64encode() 转换;
- 将结果写入 self.file 和 self.filename;
- 返回标准 ir.actions.act_window 动作(非 act_url),指向自身视图并触发下载。
@api.multi
def download_patient_report(self):
self.ensure_one() # ✅ 强制单记录,避免批量操作异常
# 构建患者查询条件
domain = []
if self.gender_filter:
domain.append(('gender', '=', self.gender_filter))
patients = self.env['hospital.patient'].search(domain)
if not patients:
raise UserError(_('No patients found matching the criteria.'))
# 生成CSV内容(使用StringIO + DictWriter,确保字段顺序与编码安全)
output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=['Name', 'Age', 'Gender'])
writer.writeheader()
for patient in patients:
writer.writerow({
'Name': patient.name or '',
'Age': str(patient.age) if patient.age else '',
'Gender': dict(patient._fields['gender'].selection).get(patient.gender, patient.gender) or ''
})
csv_data = output.getvalue()
output.close()
# ? 关键:Base64编码并写入binary字段
self.file = base64.b64encode(csv_data.encode('utf-8'))
self.filename = f'patient_report_{fields.Date.today().strftime("%Y%m%d")}.csv'
# ✅ 返回标准窗口动作(自动触发浏览器下载)
return {
'type': 'ir.actions.act_window',
'res_model': 'report.patient.wizard',
'view_mode': 'form',
'res_id': self.id,
'target': 'new',
'context': dict(self.env.context, hide_download_button=True), # 可选:隐藏重复按钮
}-
更新XML视图:添加隐藏字段与下载按钮
在表单视图中显式声明 file 和 filename 字段(设为 invisible="1"),并确保按钮调用正确方法:
<record id="report_patient_view" model="ir.ui.view">
<field name="name">Report Patient</field>
<field name="model">report.patient.wizard</field>
<field name="arch" type="xml">
<form string="Report Patient">
<group col="1">
<field name="gender_filter"/>
</group>
<!-- ? 隐藏字段:供系统读取文件内容 -->
<field name="file" invisible="1"/>
<field name="filename" invisible="1"/>
<footer>
<button name="download_patient_report"
string="Download CSV"
type="object"
class="btn btn-primary"/>
<button string="Cancel" class="btn btn-secondary" special="cancel"/>
</footer>
</form>
</field>
</record>⚠️ 注意事项与最佳实践
- 编码一致性:务必使用 .encode('utf-8') 再 base64.b64encode(),否则中文等非ASCII字符将乱码;
- 内存安全:io.StringIO 适用于中小数据量;超大数据建议改用 io.BytesIO + csv.writer(避免字符串编码转换开销);
- 字段命名规范:field 参数必须与模型中定义的字段名完全一致(此处为 file);
- 附件管理:设置 attachment=True(默认)可让文件存入IrAttachment表,便于审计;若设为 False,则仅临时存在缓存中;
- 用户体验优化:可通过 filename 字段控制下载时的默认文件名,避免浏览器使用随机ID;
- 权限校验:如需限制导出权限,可在方法开头添加 self.env.user.has_group('your_module.group_export') 校验。
通过以上结构化实现,即可稳定、安全地支持用户按性别筛选后一键导出结构化CSV报告,彻底规避路由字段缺失错误,并符合Odoo官方推荐的最佳实践。

















