0
votes

In my project i have an entity with a binary attribute (shape). I want to raise a message (validationError) if the user uploads a file with the wrong extention for that shape attribute in the form in the form. How should i do it?

I have done this so far but is nor working

 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 ")

and in the view

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

2 Answers

1
votes

The method is invoked on a pseudo-record that contains the values present in the form, we need to check only the shape_filename field value.

shape_filename field is of type Char when it has a value it should be a string.we do not need to convert it to a string.

Empty strings are concidered False when they are tested for truth value (type(name) != bool).

The default value for attachment attribute is True

Example:

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 ")

The onchange method can be reduced to :

@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 ")
0
votes

For a regular filename, you can use this:

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