翼度科技»论坛 编程开发 python 查看内容

odoo 给列表视图添加按钮实现数据文件导入

7

主题

7

帖子

21

积分

新手上路

Rank: 1

积分
21
实践环境

Odoo 14.0-20221212 (Community Edition)
代码实现

模块文件组织结构

说明:为了更好的表达本文主题,一些和主题无关的文件、代码已略去
  1. odoo14\custom\estate
  2. │  __init__.py
  3. │  __manifest__.py
  4. ├─models
  5. │  estate_customer.py
  6. │  __init__.py
  7. ├─security
  8. │      ir.model.access.csv
  9. ├─static
  10. │  ├─img
  11. │  │      icon.png
  12. │  │
  13. │  └─src
  14. │      ├─js
  15. │      │      estate_customer_tree_upload.js
  16. │      │
  17. │      └─xml
  18. │              estate_customer_tree_view_buttons.xml
  19. └─views
  20.       estate_customer_views.xml
  21.       estate_menus.xml
  22.       webclient_templates.xml
复制代码
测试模型定义

odoo14\custom\estate\models\estate_customer.py
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import base64
  4. import openpyxl
  5. from odoo.exceptions import UserError
  6. from odoo import models, fields, _ # _ = GettextAlias()
  7. from tempfile import TemporaryFile
  8. class EstateCustomer(models.Model):
  9.     _name = 'estate.customer'
  10.     _description = 'estate customer'
  11.     name = fields.Char(required=True)
  12.     age = fields.Integer()
  13.     description = fields.Text()
  14.     def create_customer_from_attachment(self, attachment_ids=None):
  15.         """
  16.         :param attachment_ids: 上传的数据文件ID列表
  17.         """
  18.         attachments = self.env['ir.attachment'].browse(attachment_ids)
  19.         if not attachments:
  20.             raise UserError(_("未找到上传的文件"))
  21.         for attachment in attachments:
  22.             file_name_suffix = attachment.name.split('.')[-1]
  23.             # 针对文本文件,暂时不实现数据存储,仅演示如何处理文本文件
  24.             if file_name_suffix in ['txt', 'html']: # 文本文件
  25.                 lines = base64.decodebytes(attachment.datas).decode('utf-8').split('\n')
  26.                 for line in lines:
  27.                     print(line)
  28.             elif file_name_suffix in ['xlsx', 'xls']: # excel文件
  29.                 file_obj = TemporaryFile('w+b')
  30.                 file_obj.write(base64.decodebytes(attachment.datas))
  31.                 book = openpyxl.load_workbook(file_obj, read_only=False)
  32.                 sheets = book.worksheets
  33.                 for sheet in sheets:
  34.                     rows = sheet.iter_rows(min_row=2, max_col=3) # 从第二行开始读取,每行读取3列
  35.                     for row in rows:
  36. <?xml version="1.0"?>
  37. <odoo>
  38.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  39.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  40.     </menuitem>
  41. </odoo>name_cell, age_cell, description_cell = row
  42. <?xml version="1.0"?>
  43. <odoo>
  44.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  45.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  46.     </menuitem>
  47. </odoo>self.create({'name': name_cell.value, 'age': age_cell.value, 'description': description_cell.value})
  48.             else:
  49.                 raise UserError(_("不支持的文件类型,暂时仅支持.txt,.html,.xlsx,.xls文件"))
  50.             return {
  51.                 'action_type': 'reload', # 导入成功后,希望前端执行的动作类型, reload-刷新tree列表, do_action-执行action
  52.             }
复制代码
说明:

  • 函数返回值,具体需要返回啥,实际取决于下文js实现(上传成功后需要执行的操作),这里结合实际可能的需求,额外提供另外几种返回值供参考:
形式1:实现替换当前页面的效果
  1. return {
  2.     'action_type': 'do_action',
  3.     'action': {
  4.         'name': _('导入数据'),        
  5.         'res_model': 'estate.customer',
  6.         'views': [[False, "tree"]],
  7.         'view_mode': 'tree',
  8.         'type': 'ir.actions.act_window',
  9.         'context': self._context,
  10.         'target': 'main'
  11.     }
  12. }
复制代码
形式2:弹出对话框效果
  1. return {
  2.     'action_type': 'do_action',
  3.     'action': {
  4.         'name': _('导入成功'),        
  5.         'res_model': 'estate.customer.wizard',
  6.         'views': [[False, "form"]],
  7.         'view_mode': 'form',
  8.         'type': 'ir.actions.act_window',
  9.         'context': self._context,
  10.         'target': 'new'
  11.     }
  12. }
复制代码
说明:打开estate.customer.wizard默认form视图
形式3:实现类似浏览器刷新当前页面效果
  1. return {
  2.     'action_type': 'do_action',
  3.     'action': {
  4.         'type': 'ir.actions.client',
  5.         'tag': 'reload' # 或者替换成 'tag': 'reload_context',
  6.     }
  7. }
复制代码
odoo14\custom\estate\models\__init__.py
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. from . import estate_customer
复制代码
测试数据文件

mydata.xlsx
姓名年龄备注张三30喜好运动李四28喜欢美食王五23测试模型视图定义

odoo14\custom\estate\views\estate_customer_views.xml
  1. <?xml version="1.0"?>
  2. <odoo>
  3.     <record id="link_estate_customer_action" model="ir.actions.act_window">
  4.         <field name="name">顾客信息</field>
  5.         <field name="res_model">estate.customer</field>
  6.         <field name="view_mode">tree,form</field>
  7.     </record>
  8.     <record id="estate_customer_view_tree" model="ir.ui.view">
  9.         <field name="name">estate.customer.tree</field>
  10.         <field name="model">estate.customer</field>
  11.         <field name="arch" type="xml">
  12.             <tree js_ limit="15">
  13.                 <field name="name" string="Title"/>
  14.                 <field name="age" string="Age"/>
  15.                 <field name="description" string="Remark"/>
  16.             </tree>
  17.         </field>
  18.     </record>
  19.     <record id="estate_customer_view_form" model="ir.ui.view">
  20.         <field name="name">estate.customer.form</field>
  21.         <field name="model">estate.customer</field>
  22.         <field name="arch" type="xml">
  23.             <form>
  24.                 <sheet>
  25.                     <group>
  26. <?xml version="1.0"?>
  27. <odoo>
  28.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  29.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  30.     </menuitem>
  31. </odoo><field name="name" />
  32. <?xml version="1.0"?>
  33. <odoo>
  34.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  35.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  36.     </menuitem>
  37. </odoo><field name="age"/>
  38. <?xml version="1.0"?>
  39. <odoo>
  40.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  41.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  42.     </menuitem>
  43. </odoo><field name="description"/>
  44.                     </group>
  45.                 </sheet>
  46.             </form>
  47.         </field>
  48.     </record>
  49. </odoo>
复制代码
说明:,其中estate_customer_tree为下文javascript中定义的组件,实现添加自定义按钮;limit 设置列表视图每页最大显示记录数
菜单定义

odoo14\custom\estate\views\estate_menus.xml
  1. <?xml version="1.0"?>
  2. <odoo>
  3.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  4.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  5.     </menuitem>
  6. </odoo>
复制代码
estate_customer_tree 组件定义

js实现

为列表视图添加自定义上传数据文件按钮
odoo14\custom\estate\static\src\js\estate_customer_tree_upload.js
  1. odoo.define('estate.upload.customer.mixin', function (require) {"use strict";    var core = require('web.core');    var _t = core._t;    var qweb = core.qweb;    var UploadAttachmentMixin = {        start: function () {            // 定义一个唯一的fileUploadID(形如 my_file_upload_upload737)和一个回调方法            this.fileUploadID = _.uniqueId('my_file_upload');            $(window).on(this.fileUploadID, this._onFileUploaded.bind(this));            return this._super.apply(this, arguments);        },        _onAddAttachment: function (ev) {            // 一旦选择了附件,自动提交表单(关闭上传对话框)            var $input = $(ev.currentTarget).find('input.o_input_file');            if ($input.val() !== '') {                 // o_estate_customer_upload定义在对应的QWeb模版中                var $binaryForm = this.$('.o_estate_customer_upload form.o_form_binary_form');                $binaryForm.submit();            }        },        _onFileUploaded: function () {            // 创建附件后的回调,根据附件ID执行相关处程序            var self = this;            var attachments = Array.prototype.slice.call(arguments, 1);            // 获取附件ID            var attachent_ids = attachments.reduce(function(filtered, record) {                if (record.id) {                    filtered.push(record.id);                }                return filtered;            }, []);            // 请求模型方法            return this._rpc({                model: 'estate.customer',  //模型名称                method: 'create_customer_from_attachment', // 模型方法                args: ["", attachent_ids],                context: this.initialState.context,            }).then(function(result) { // result为一个字典                if (result.action_type == 'reload') {                    self.trigger_up('reload'); // 实现在不刷新页面的情况下,刷新列表视图// 此处换成 self.reload(); 发现效果也是一样的                } else if (result.action_type == 'do_action') {                    self.do_action(result.action); // 执行action动作                } else { // 啥也不做                }                // 重置 file input, 如果需要,可以再次选择相同的文件,如果不添加以下这行代码,不刷新当前页面的情况下,无法重复导入相同的文件                self.$('.o_estate_customer_upload .o_input_file').val('');             }).catch(function () {<?xml version="1.0"?>
  2. <odoo>
  3.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  4.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  5.     </menuitem>
  6. </odoo>        self.$('.o_estate_customer_upload .o_input_file').val('');            });        },        _onUpload: function (event) {            var self = this;            // 如果隐藏的上传表单不存在则创建            var $formContainer = this.$('.o_content').find('.o_estate_customer_upload');            if (!$formContainer.length) {                // estate.CustomerHiddenUploadForm定义在对应的QWeb模版中                $formContainer = $(qweb.render('estate.CustomerHiddenUploadForm', {widget: this}));                $formContainer.appendTo(this.$('.o_content'));            }            // 触发input选取文件            this.$('.o_estate_customer_upload .o_input_file').click();        },    }    return UploadAttachmentMixin;});odoo.define('estate.customer.tree', function (require) {"use strict";    var core = require('web.core');    var ListController = require('web.ListController');    var ListView = require('web.ListView');    var UploadAttachmentMixin = require('estate.upload.customer.mixin');    var viewRegistry = require('web.view_registry');    var CustomListController = ListController.extend(UploadAttachmentMixin, {        buttons_template: 'EstateCustomerListView.buttons',        events: _.extend({}, ListController.prototype.events, {            'click .o_button_upload_estate_customer': '_onUpload',            'change .o_estate_customer_upload .o_form_binary_form': '_onAddAttachment',        }),    });    var CustomListView = ListView.extend({        config: _.extend({}, ListView.prototype.config, {            Controller: CustomListController,        }),    });    viewRegistry.add('estate_customer_tree', CustomListView);});
复制代码
说明:如果其它模块的列表视图也需要实现类似功能,想复用上述js,需要替换js中以下内容:

  • 修改estate.upload.customer.mixin为其它自定义全局唯一值
  • 替换o_estate_customer_upload为在对应按钮视图模板中定义的对应class属性值
  • 替换estate.CustomerHiddenUploadForm为在对应按钮视图模板中定义的隐藏表单模版名称
  • 替换EstateCustomerListView.buttons为对应按钮视图模板中定义的按钮模版名称
  • 根据需要替换 this._rpc函数中的model参数值("estate.customer"),method参数值("create_customer_from_attachment"),必要的话,修改then函数实现。
  • 替换estate_customer_tree为自定义全局唯一值
  • do_action 为 Widget() 的快捷方式(定义在odoo14\odoo\addons\web\static\src\js\core\service_mixins.js中),用于查找当前action管理器并执行action -- do_action函数的第一个参数,格式如下:
    1. {
    2.     'type': 'ir.actions.act_window',
    3.     'name': _('导入数据'),        
    4.     'res_model': 'estate.customer',
    5.     'views': [[False, "tree"], [False, "form"]],
    6.     'view_mode': 'tree',
    7.     'context': self._context,
    8.     'target': 'current'
    9. }
    复制代码
加载js脚本xml文件定义

odoo14\custom\estate\views\webclient_templates.xml
  1. <?xml version="1.0"?>
  2. <odoo>
  3.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  4.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  5.     </menuitem>
  6. </odoo>              
复制代码
按钮视图模板定义

odoo14\custom\estate\static\src\xml\estate_customer_tree_view_buttons.xml
  1. <?xml version="1.0"?>
  2. <odoo>
  3.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  4.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  5.     </menuitem>
  6. </odoo><?xml version="1.0"?>
  7. <odoo>
  8.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  9.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  10.     </menuitem>
  11. </odoo><?xml version="1.0"?>
  12. <odoo>
  13.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  14.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  15.     </menuitem>
  16. </odoo>/web/binary/upload_attachment<?xml version="1.0"?>
  17. <odoo>
  18.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  19.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  20.     </menuitem>
  21. </odoo><?xml version="1.0"?>
  22. <odoo>
  23.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  24.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  25.     </menuitem>
  26. </odoo><?xml version="1.0"?>
  27. <odoo>
  28.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  29.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  30.     </menuitem>
  31. </odoo>                    Upload            
复制代码
说明:
t-name:定义模版名称
t-extend:定义需要继承的模板。
t-jquery:接收一个CSS 选择器,用于查找上下文中,同CSS选择器匹配的元素节点(为了方便描述,暂且称之为上下文节点)
t-operation:设置需要对上下文节点执行的操作(为了方便描述,暂且将t-operation属性所在元素称为模板元素),可选值如下:

  • append
    将模板元素内容(body)追加到上下文节点的最后一个子元素后面。
  • prepend
    将模板元素内容插入到上下文节点的第一个子元素之前。
  • before
    将模板元素内容插入到上下文节点之前。
  • after
    将模板元素内容插入到上下文节点之后。
  • inner
    将模板元素内容替换上下文节点元素内容(所有子节点)
  • replace
    将模板元素内容替换上下文节点
  • attributes
    模版元素内容应该是任意数量的属性元素,每个元素都有一个名称属性和一些文本内容,上下文节点的命名属性将被设置为属性元素的值(如果已经存在则替换,如果不存在则添加)
注意:参考官方文档,t-extend这种继承方式为旧的继承方式,已废弃,笔者实践了最新继承方式,如下
  1. <?xml version="1.0"?>
  2. <odoo>
  3.     <menuitem id="test_menu_root" name="Real Estate" web_icon="estate,static/img/icon.png">        
  4.         <menuitem id="data_import_testing" name="数据导入测试" action="link_estate_customer_action"/>
  5.     </menuitem>
  6. </odoo>Upload            
复制代码
发现会报错:
  1. ValueError: Module ListView not loaded or inexistent, or templates of addon being loaded (estate) are misordered
复制代码
参考连接:https://www.odoo.com/documentation/14.0/zh_CN/developer/reference/javascript/qweb.html
模型访问权限配置

odoo14\custom\estate\security\ir.model.access.csv
  1. id,name,model_id/id,group_id/id,perm_read,perm_write,perm_create,perm_unlink
  2. access_estate_customer_all_perm,access_estate_customer_all_perm,model_estate_customer,base.group_user,1,1,1,1
复制代码
模块其它配置

odoo14\custom\estate\__init__.py
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. from . import models
复制代码
odoo14\custom\estate\__manifest__.py
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. {
  4.     'name': 'estate',
  5.     'depends': ['base'],
  6.     'data':[
  7.         'security/ir.model.access.csv',
  8.         'views/webclient_templates.xml',
  9.         'views/estate_customer_views.xml',        
  10.         'views/estate_menus.xml'
  11.     ],
  12.     'qweb':[# templates定义文件不能放data列表中,提示不符合shema,因为未使用<odoo>元素进行“包裹”
  13.         'static/src/xml/estate_customer_tree_view_buttons.xml',
  14.     ]
  15. }
复制代码
最终效果



来源:https://www.cnblogs.com/shouke/p/17135868.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具