forvas
forvas

Reputation: 10189

Why a binary filename field is missing in a Transient Model in Odoo 9?

I created a TransientModel which has a binary field expecting a ZIP file, thus I want to work with its filename to check that the file uploaded by the user is actually a ZIP. So I did as always:

CODE

XML

<field name="filename" invisible="0"/>
<field name="source_file" widget="binary" filename="filename"/>

<button name="import_zip" string="Import" type="object" class="oe_highlight"/>

Python 2.7

class EasyImport(models.TransientModel):
    _name = 'easy.import'

    source_file = fields.Binary(
        string='Choose a ZIP File',
        required=True,
    )
    filename = fields.Char(
        string='Filename',
        readonly=True,
        required=True,
    )

    @api.onchange('filename')
    def onchange_filename(self):
        _logger.critical(self.filename)  # Returns the filename OK

    @api.multi
    def import_zip(self):
        self.ensure_one()
        _logger.critical(self.filename)  # Returns False

PURPOSE

Reject non-ZIP files. Or at least, read the field filename.

THE PROBLEM

The filename field is always False (except in onchange method).

I tried to get its value in a constraint, in the import_zip method... but it returns False. However, I can see the filename in the interface as I am showing the field filename in the XML view, and it is right and automatically filled in.

I have an ugly workaround with a computed field to work with the filename, but I want to improve this and know what is happening here.

Any ideas? Thank you!

Upvotes: 1

Views: 726

Answers (1)

forvas
forvas

Reputation: 10189

The problem is not related to transient models nor binary fields nor any of those.

The field filename is readonly and I have just realised what happened with readonly fields combined with onchange methods, there is a big mistake in Odoo, in my opinion, still with no fix -at least in version 9-:

If you modify a readonly field in an onchange event, you can work OK with its new value until you save the record. When this happens, the new value turns into the old one, and every method which uses it will get the old value.

In my case, I saw the filename OK in the onchange method because the record was not saved, but when I clicked on the button which executes import_zip method, before executing its content, the record is stored and due to the Odoo mistake the filename value was replaced by its old value (which is always False).

So basically the solution is making not readonly the field fieldname:

filename = fields.Char(
    string='Filename',
    readonly=False,
    required=True,
)

And in XML make it invisible to avoid inconsistencies:

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

Upvotes: 1

Related Questions