Chen Jian

导航

 

最近的一个项目要求在Product_Template中增加类似与HTML中<img src=”" />的形式的图片

product_img_extra.py

from osv import osv, fields  
import urllib2  
import base64  
class product_template_img(osv.osv):  
    _name = 'product.template'  
    _inherit = 'product.template'  
    _description = 'Product Extra Image'  
    def _get_image(self, cursor, user, ids, name, arg, context=None):  
        image = {}  
        opener = urllib2.build_opener()  
        res = self.read(cursor, user, ids, ['image_link'])  
        image_link = res[0]['image_link']  
        if image_link:  
            pic = base64.encodestring(opener.open(image_link).read())  
            for id in ids:  
                image[id] = pic  
        return image  
    _columns = {  
        'image_link' : fields.char('Image Link', size=180),  
        'image' : fields.function(_get_image, method=True, string='Product Image', type='binary', store=False),   
    }  
product_template_img()

product_img_extra_view.xml

<?xml version="1.0" encoding="utf-8"?>  
    <openerp>  
        <data>  
            <record id="product_img_view" model="ir.ui.view">  
                <field name="name">product.template.product.form</field>  
                <field name="model">product.template</field>  
                <field name="type">form</field>  
                <field name="inherit_id" ref="product.product_template_form_view" />  
                <field name="arch" type="xml">  
                    <field name="name" position="before">  
                        <field name="image" widget="image" nolabel="1" img_width="168" img_height="168" colspan="4"/>  
                        <field name="image_link" colspan="4"/>  
                    </field>  
                </field>  
            </record>  
        </data>  
    </openerp>

由于OpenERP的基本开发概念的其中一点是读取数据库动态生成界面.这时我就想到了使用fields.function来在界面生成时做一些特别的处理.
product_img_extra.py 中的_columns将对productTemplate增加image_link和image两个column.其中image_link用于保存图片链接的column,当界面生成时通过链接读取图片.image为显示图片的column,但由于store已设置为False所以不会直接保存到数据库中,而只会在界面生成时运行.

因为需要读取外部链接,所以需要用到Python自带的urllib2模块,值得注意的是opener.open(image_link).read()获取回来的虽然已经是二进制数据,但仍需要使用base64.encodestring对其进行转码才可以被所识别.

posted on 2014-02-10 11:30  Chen Jian  阅读(533)  评论(0编辑  收藏  举报