I need to create a ir.attachment field to upload datas by the user side,but i have to restrict the data type and size,how can i achieve it
my python field is :-
test = fields.Many2many('ir.attachment',string='Test')
You can use constrains to check test
field.
Use mimetype
and file_size
fields to check the data type and size, the attachment size shown in the many2many list is computed using binaryToBinsize
function from core/utils.js
which divides the length by 1.37
then convert it to human size (divide by 1024 repeatedly).
Example:
Force users to select only text files smaller than 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!")
To prevent users from creating attachments that are not plain text files smaller than 10M using the test field list:
Pass file_size
and mimetype
in the context:
<field name="test" context="{'file_size': 10*1024*1024, 'mimetype': 'text/plain'}">
And add the constraints in the ir.attachment
model.
Example:
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']))