如何在Odoo中使用onchange函数检查文件扩展名



在我的项目中,我有一个具有二进制属性(shape(的实体。如果用户在表单中的表单中上传了一个具有错误扩展名的shape属性的文件,我想引发一条消息(validationError(。我应该怎么做?

到目前为止,我已经这样做了,但也没有工作

shape = fields.Binary(string='Shape', required=True, attachment=True)
shape_filename = fields.Char()
def _check_file_extension(self, name, ext):
if type(name) != bool:
if not str(name).endswith(ext):
return False
return True
return False
@api.onchange('shape_filename')
def _onchange_shape(self):
if self.id and not self._check_file_extension(self.shape_filename,
'.zip'):
raise ValidationError("Shape must be a .zip file ")

并且在视图中

<field name="shape" widget="download_link" filename="shape_filename" options="{'filename': 'shape_filename'}"/>
<field name="shape_filename" readonly="1"  invisible="1" force_save="1"/>

方法是在包含表单中存在的值的伪记录上调用的,我们只需要检查shape_filename字段值。

shape_filename字段的类型为Char,当它有值时,它应该是字符串。我们不需要将它转换为字符串。

当测试空字符串的真值(type(name) != bool(时,它们被排序为False

附件属性的默认值为True

示例

def _check_file_extension(self, name, ext):
if name:
if not name.endswith(ext):
return False
return True
return False
@api.onchange('shape_filename')
def _onchange_shape(self):
if not self._check_file_extension(self.shape_filename, '.zip'):
raise ValidationError("Shape must be a .zip file ")

onchange方法可以简化为:

@api.onchange('shape_filename')
def _onchange_shape(self):
if self.shape_filename and not self.shape_filename.endswith('.zip'):
raise ValidationError("Shape must be a .zip file ")

对于常规文件名,可以使用以下命令:

def _check_file_extension(name, ext):
if name.split(".")[-1] != ext:
return False
return True

最新更新