限制 ir.attachment 字段 odoo 12 中数据的大小和类型

limiting the size and type of data in ir.attachment field odoo 12

我需要创建一个ir.attachment字段来由用户端上传数据,但我必须限制数据类型和大小,我该如何实现

我的 python 字段是:-

test = fields.Many2many('ir.attachment',string='Test')

您可以使用 constrains 检查 test 字段。

使用 mimetypefile_size 字段检查数据类型和大小,many2many 列表中显示的附件大小是使用 binaryToBinsize 函数从 core/utils.js 计算得出的将长度除以 1.37 然后将其转换为人类大小(重复除以 1024)。

示例:

强制用户select 只能使用小于 10M 的文本文件

@api.one
@api.constrains('test')
def _check_attachments(self):
    for attachment in self.test:
        if attachment.mimetype != 'text/plain' or attachment.file_size > 10 * 1024 * 1024:
            raise ValidationError("Only text files smaller than 10M are allowed!")

为了防止用户使用测试字段列表创建不是小于 10M 的纯文本文件的附件:

在上下文中传递 file_sizemimetype

<field name="test" context="{'file_size': 10*1024*1024, 'mimetype': 'text/plain'}">

并在 ir.attachment 模型中添加约束。

示例:

def human_size(size):
    units = "Bytes,Kb,Mb,Gb,Tb,Pb,Eb,Zb,Yb".split(',')
    i = 0
    while size >= 1024:
        size /= 1024
        i += 1
    return "%.4g %s " % (size, units[i])


class IrAttachment(models.Model):
    _inherit = 'ir.attachment'

    @api.one
    @api.constrains('mimetype', 'file_size')
    def _check_mimetype_file_size(self):
        if 'mimetype' in  self.env.context and self.env.context['mimetype'] != self.mimetype:
            raise ValidationError("Only text files can be uploaded!")
        if 'file_size' in self.env.context and self.env.context['file_size'] < self.file_size:
            raise ValidationError("Only text files smaller than %s are allowed!" % human_size(self.env.context['file_size']))