繁体   English   中英

如何在 Odoo 中将默认图像设置为二进制字段?

[英]How to set default image to binary field in Odoo?

在我的模块中,我有一个二进制字段,我使用图像小部件显示该字段,但是当该字段没有值时,它会在用户界面中显示一个空白区域。 我想知道如何为该字段设置默认图像,因此当用户没有为图像字段设置值时,界面将显示默认图像。 我正在使用 odoo 12

将图像保存在您的自定义模块中。 将 full_path 替换为您的路径。

import base64
...

class Demo(models.Model):
...
    def _read_image(self):
        with open(full_path, 'rb') as img:
            image = base64.b64encode(img.read())
        return image

    Image = fields.Binary('Image', default=_read_image)

我尝试了这样的事情,它为我的目的工作:

import base64

# some stuff

class YourModel(models.Model):

    # some stuff

    image = fields.Binary(compute='_set_image')

    # some stuff

    def _set_image(self):
        for record in self:
            path = record.get_image_path() #: image path in odoo folder structure, example: /odoo/images/<file>
            if not record.image:
                with open(path, 'rb') as img:
                    record.image = base64.b64encode(img.read())
  

get_image_path()返回的路径示例:

'/odoo/images/default_image.png'

在视图文件中:

<record ...>
    <!-- some stuff for form view -->
    <field name="arch" type="xml">
        <!-- some stuff -->
        <field name="image" widget="image"/>
    </field>
</record>

尝试这个:

自定义.py

import base64

from odoo import api, fields, models
from odoo import tools, _
from odoo.modules.module import get_module_resource

class MyCustomModel(models.Model):
    _name = "my.custom.model"

    @api.model
    def _default_image(self):
        image_path = get_module_resource('my_custom_module', 'static/src/img', 'default_image.png')
        return tools.image_resize_image_big(base64.b64encode(open(image_path, 'rb').read()))

    image = fields.Binary(
        "Photo", default=_default_image, attachment=True,
        help="This field holds the image used as photo for the employee, limited to 1024x1024px.")

custom_view.xml

<field name="image" widget='image' class="oe_avatar" options='{"preview_image":"image_medium"}'/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM