Odoo13迁移至Odoo15遇AttributeError:找不到mako_template_env属性
问题描述
函数在Odoo 13中运行正常,但迁移至Odoo 15时抛出以下错误:
AttributeError: module 'odoo.addons.mail.models.mail_template' has no attribute 'mako_template_env'
原函数代码如下:
def render_doc(self, doctype): types = {'cert': 'Certificate', 'pol_doc': 'Policy Document', 'guarantee_cert': 'Guarantee Policy Certificate'} if doctype not in types.keys(): raise UserError(_('Document must be of type cert or pol_doc')) prod_doc_ids = self.policy_id.product_id.product_doc_ids doc = prod_doc_ids.filtered( lambda c: c.doc_type == doctype) if prod_doc_ids else False if doc: body = doc.body else: body = f"<p><strong>{types[doctype]}</strong> is not yet \ setup for <strong>{self.policy_id.product_id.name}.</strong>\ Please contact the system administrator.</p>" return mail_template.mako_template_env.from_string(body).render({'object': self})
解决方案
Odoo 15中已移除mail_template模块级别的mako_template_env属性,需改用官方提供的模板渲染方式,以下是两种可行方案:
方案一:使用官方工具函数(推荐)
直接调用odoo.tools.mail.render_template函数,该函数会自动处理Mako模板渲染,并将当前记录作为object传入模板,与原逻辑完全匹配:
from odoo.tools.mail import render_template def render_doc(self, doctype): types = {'cert': 'Certificate', 'pol_doc': 'Policy Document', 'guarantee_cert': 'Guarantee Policy Certificate'} if doctype not in types.keys(): raise UserError(_('Document must be of type cert or pol_doc')) prod_doc_ids = self.policy_id.product_id.product_doc_ids doc = prod_doc_ids.filtered( lambda c: c.doc_type == doctype) if prod_doc_ids else False if doc: body = doc.body else: body = f"<p><strong>{types[doctype]}</strong> is not yet \ setup for <strong>{self.policy_id.product_id.name}.</strong>\ Please contact the system administrator.</p>" # 替换原mako环境调用为官方渲染函数 return render_template(body, self._name, self.id)
方案二:获取官方维护的Mako环境
如果需要自定义渲染上下文,可通过邮件模板模型的_get_mako_env方法获取官方Mako环境:
def render_doc(self, doctype): types = {'cert': 'Certificate', 'pol_doc': 'Policy Document', 'guarantee_cert': 'Guarantee Policy Certificate'} if doctype not in types.keys(): raise UserError(_('Document must be of type cert or pol_doc')) prod_doc_ids = self.policy_id.product_id.product_doc_ids doc = prod_doc_ids.filtered( lambda c: c.doc_type == doctype) if prod_doc_ids else False if doc: body = doc.body else: body = f"<p><strong>{types[doctype]}</strong> is not yet \ setup for <strong>{self.policy_id.product_id.name}.</strong>\ Please contact the system administrator.</p>" # 获取官方Mako环境 mako_env = self.env['mail.template']._get_mako_env() return mako_env.from_string(body).render({'object': self})
内容的提问来源于stack exchange,提问作者MarkHenri
相关产品推荐
相关产品推荐

