Web 表单是收集用户信息的重要工具,包括联系方式、教育背景、职业历史等。此外,它们还有助于有效地进行调查。Web 表单允许创建各种字段类型,帮助系统地收集数据。其中,附件字段尤为突出。在本文中,我们将探讨在Odoo16中建立附件字段以存储从 Web 表单上传的文件的过程。
首先,我们必须在模型中创建一个字段来容纳附件。Odoo 提供了一个名为“ir.attachment”的模型来管理附件文件。在我们的例子中,我们继承了“res.partner”模型来合并附件字段:
attachment_ids = fields.Many2many('ir.attachment', string='Attachments')
ir.attachment 是 Odoo 指定的用于存储最终用户提交的附件的模型。在本指南中,我们将说明如何利用此模型通过 Web 表单上传文件。
要实现我们的 Web 表单,我们需要制作一个 XML 文件。在此文件中,插入“form”标签并定义要包含的字段。附件输入字段可以放在此表单中的任何位置。以下是包含各种字段的示例,包括附件字段。将此字段合并到“form”标签中。“form”标签带有多个属性,例如“class”、“action”、“method”、“enctype”等。值得注意的是,“enctype”属性在处理附件时起着至关重要的作用。它指定文件中的字符不应被编码。以下是带有“enctype”属性的“form”标签示例:
<form action="/my/account" method="post"
enctype="multipart/form-data">
<div class="row o_portal_details">
<div class="col-lg-8">
<div class="row">
<t t-call="portal.portal_my_details_fields"/>
<div t-attf-class="mb-3 #{error.get('name') and 'o_has_error' or ''} col-xl-6">
<label class="col-form-label" for="attachment">
Attach file
</label>
<input type="file"
name="att"
accept=".pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
required="required"/>
</div>
<input type="hidden" name="redirect"
t-att-value="redirect"/>
</div>
<div class="clearfix">
<button type="submit"
class="btn btn-primary float-end mb32 ">
Confirm
<span class="fa fa-long-arrow-right"/>
</button>
</div>
</div>
</div>
</form>
在控制器中,您必须开发一个函数来对文件进行编码并将其保存到数据库。以下是示例代码片段:
import base64
from odoo.addons.portal.controllers.portal import CustomerPortal
from odoo.http import request, route
class ResPartnerController(CustomerPortal):
@route(['/my/account'], type='http', auth='public', website=True)
def account(self, redirect=None, **post):
res = super().account()
partner_id = request.env.user.partner_id
Attachment = request.env['ir.attachment']
file = post.get('attachment')
attachment_id = Attachment.create({
'name': file.file_name,
'type': 'binary',
'datas': base64.encodebytes(file.read()),
'res_model': partner_id._name,
'res_id': partner_id.id
})
partner_id.update({
'attachment': [(4, attachment_id.id)],
})
return res
'base64.b64encode(file.read())' 行对上传文件的内容进行编码。它读取文件内容,直到遇到空字符串,并返回编码数据以及尾随换行符 ('\n')。结果,该文件存储在数据库中,演示了如何通过 Web 表单上传文件。