Skip to Content
Menu
This question has been flagged
4 Replies
13349 Views

Hi all developers, I would like to upload only .pdf file , so what can I do ? if my field like this :

file = fields.Binary(string='file', attachment=True)

Avatar
Discard
Author Best Answer

Thank you , Ravi Gadhia and Thank you Zbik ..Now I can solve with this :

In Model,

file = fields.Binary(string='file', attachment=True)

file_name = fields.Char("File Name")

@api.constrains('file')
def _check_file(self):
if str(self.file_name.split(".")[1]) != 'pdf' :
    raise ValidationError("Cannot upload file different from .pdf file")

In View,

<field name="file" filename="file_name"/>

<field name="file_name" invisible="1"/>


=> Help to vote if this solve your problem too
Avatar
Discard
Best Answer
Hello, I have a little supplement after reading the first answer. To be on the safe side, the module will receive a different filename, and we should use the .endwith function to determine the end of the file. 

As shown in the following code:

In model:

file = fields.Binary(string='file', attachment=True)
filename = fields.Char()

@api.constrains('file', 'filename')
def get_data(self):
if not self.filename.endswith('.pdf'): # check if file pdf
raise ValidationError('your error message')
else:
pass


In views:

<field name="file" filename="filename"/>

<field name="filename" invisible="1"/>
Avatar
Discard
Best Answer

Unfortunately, there is no built-in option to add accept param by binary field definition so you have to do customization for it.

Good news is that in master new PR landed in the master to achieve it and available in next versions 14.0 :)

ref: https://github.com/odoo/odoo/pull/38351​    

https://github.com/odoo/odoo/commit/e981e3312d66cd6fcddef05feda0f49b37a4c858


Note: it's a client-side option so user still can upload any file by removing the filter from browse window. if you want strict restriction then detect file type from binary content at server side

Avatar
Discard

Thanks :)

Best Answer

Use the constrains decorator to examine the type of data being loaded. See constrains documentation

Example:

@api.constrains('name', 'description')
def _check_description(self):
    if self.name == self.description:
        raise ValidationError("Fields name and description must be different")

Avatar
Discard