我创建了一个 TransientModel
,它有一个需要 ZIP 文件的二进制字段,因此我想使用它的文件名来检查用户上传的文件实际上是 ZIP。所以我一如既往:
代码
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
目的
拒绝非 ZIP 文件。或者至少,读取字段文件名
。
问题
filename
字段始终为 False
(onchange
方法除外)。
我尝试在 import_zip
方法中获取约束中的值...但它返回 False
。但是,当我在 XML View 中显示字段 filename
时,我可以在界面中看到文件名,并且它是正确的并且自动填充。
我有一个丑陋的解决方法,使用计算字段来处理文件名,但我想改进它并知道这里发生了什么。
有什么想法吗?谢谢!
最佳答案
该问题与 transient 模型、二进制字段或其中任何一个都无关。
字段filename
是只读的,我刚刚意识到只读字段与onchange
方法相结合发生了什么,Odoo中有一个很大的错误,在我看来,仍然没有修复 - 至少在版本 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.
就我而言,我在 onchange
方法中看到 filename
OK,因为记录未保存,但是当我单击执行 import_zip 的按钮时
方法,在执行其内容之前,会存储记录,并且由于 Odoo 错误,filename
值被替换为其旧值(始终为 False
) .
所以基本上解决方案是不只读字段fieldname
:
filename = fields.Char(
string='Filename',
readonly=False,
required=True,
)
在 XML 中使其不可见以避免不一致:
<field name="filename" invisible="1"/>
关于python - 为什么 Odoo 9 的 transient 模型中缺少二进制文件名字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884829/