实践环境

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. └─src
  13. ├─js
  14. estate_customer_tree_upload.js

  15. └─xml
  16. estate_customer_tree_view_buttons.xml

  17. └─views
  18. estate_customer_views.xml
  19. estate_menus.xml
  20. 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. name_cell, age_cell, description_cell = row
  37. self.create({'name': name_cell.value, 'age': age_cell.value, 'description': description_cell.value})
  38. else:
  39. raise UserError(_("不支持的文件类型,暂时仅支持.txt,.html,.xlsx,.xls文件"))
  40. return {
  41. 'action_type': 'reload', # 导入成功后,希望前端执行的动作类型, reload-刷新tree列表, do_action-执行action
  42. }

说明:

  • 函数返回值,具体需要返回啥,实际取决于下文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_class="estate_customer_tree" 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. <field name="name" />
  27. <field name="age"/>
  28. <field name="description"/>
  29. </group>
  30. </sheet>
  31. </form>
  32. </field>
  33. </record>
  34. </odoo>

说明:<tree js_class="estate_customer_tree" limit="15">,其中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) {
  2. "use strict";
  3. var core = require('web.core');
  4. var _t = core._t;
  5. var qweb = core.qweb;
  6. var UploadAttachmentMixin = {
  7. start: function () {
  8. // 定义一个唯一的fileUploadID(形如 my_file_upload_upload737)和一个回调方法
  9. this.fileUploadID = _.uniqueId('my_file_upload');
  10. $(window).on(this.fileUploadID, this._onFileUploaded.bind(this));
  11. return this._super.apply(this, arguments);
  12. },
  13. _onAddAttachment: function (ev) {
  14. // 一旦选择了附件,自动提交表单(关闭上传对话框)
  15. var $input = $(ev.currentTarget).find('input.o_input_file');
  16. if ($input.val() !== '') {
  17. // o_estate_customer_upload定义在对应的QWeb模版中
  18. var $binaryForm = this.$('.o_estate_customer_upload form.o_form_binary_form');
  19. $binaryForm.submit();
  20. }
  21. },
  22. _onFileUploaded: function () {
  23. // 创建附件后的回调,根据附件ID执行相关处程序
  24. var self = this;
  25. var attachments = Array.prototype.slice.call(arguments, 1);
  26. // 获取附件ID
  27. var attachent_ids = attachments.reduce(function(filtered, record) {
  28. if (record.id) {
  29. filtered.push(record.id);
  30. }
  31. return filtered;
  32. }, []);
  33. // 请求模型方法
  34. return this._rpc({
  35. model: 'estate.customer', //模型名称
  36. method: 'create_customer_from_attachment', // 模型方法
  37. args: ["", attachent_ids],
  38. context: this.initialState.context,
  39. }).then(function(result) { // result为一个字典
  40. if (result.action_type == 'reload') {
  41. self.trigger_up('reload'); // 实现在不刷新页面的情况下,刷新列表视图// 此处换成 self.reload(); 发现效果也是一样的
  42. } else if (result.action_type == 'do_action') {
  43. self.do_action(result.action); // 执行action动作
  44. } else { // 啥也不做
  45. }
  46. // 重置 file input, 如果需要,可以再次选择相同的文件,如果不添加以下这行代码,不刷新当前页面的情况下,无法重复导入相同的文件
  47. self.$('.o_estate_customer_upload .o_input_file').val('');
  48. }).catch(function () {
  49. self.$('.o_estate_customer_upload .o_input_file').val('');
  50. });
  51. },
  52. _onUpload: function (event) {
  53. var self = this;
  54. // 如果隐藏的上传表单不存在则创建
  55. var $formContainer = this.$('.o_content').find('.o_estate_customer_upload');
  56. if (!$formContainer.length) {
  57. // estate.CustomerHiddenUploadForm定义在对应的QWeb模版中
  58. $formContainer = $(qweb.render('estate.CustomerHiddenUploadForm', {widget: this}));
  59. $formContainer.appendTo(this.$('.o_content'));
  60. }
  61. // 触发input选取文件
  62. this.$('.o_estate_customer_upload .o_input_file').click();
  63. },
  64. }
  65. return UploadAttachmentMixin;
  66. });
  67. odoo.define('estate.customer.tree', function (require) {
  68. "use strict";
  69. var core = require('web.core');
  70. var ListController = require('web.ListController');
  71. var ListView = require('web.ListView');
  72. var UploadAttachmentMixin = require('estate.upload.customer.mixin');
  73. var viewRegistry = require('web.view_registry');
  74. var CustomListController = ListController.extend(UploadAttachmentMixin, {
  75. buttons_template: 'EstateCustomerListView.buttons',
  76. events: _.extend({}, ListController.prototype.events, {
  77. 'click .o_button_upload_estate_customer': '_onUpload',
  78. 'change .o_estate_customer_upload .o_form_binary_form': '_onAddAttachment',
  79. }),
  80. });
  81. var CustomListView = ListView.extend({
  82. config: _.extend({}, ListView.prototype.config, {
  83. Controller: CustomListController,
  84. }),
  85. });
  86. viewRegistry.add('estate_customer_tree', CustomListView);
  87. });

说明:如果其它模块的列表视图也需要实现类似功能,想复用上述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_actionWidget() 的快捷方式(定义在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" encoding="utf-8"?>
  2. <odoo>
  3. <template id="assets_common" inherit_id="web.assets_common" name="Backend Assets (used in backend interface)">
  4. <xpath expr="//script[last()]" position="after">
  5. <script type="text/javascript" src="/estate/static/src/js/estate_customer_tree_upload.js"></script>
  6. </xpath>
  7. </template>
  8. </odoo>

按钮视图模板定义

odoo14\custom\estate\static\src\xml\estate_customer_tree_view_buttons.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <templates>
  3. <t t-name="estate.CustomerHiddenUploadForm">
  4. <div class="d-none o_estate_customer_upload">
  5. <t t-call="HiddenInputFile">
  6. <t t-set="multi_upload" t-value="true"/>
  7. <t t-set="fileupload_id" t-value="widget.fileUploadID"/>
  8. <t t-set="fileupload_action" t-translation="off">/web/binary/upload_attachment</t>
  9. <input type="hidden" name="model" value=""/>
  10. <input type="hidden" name="id" value="0"/>
  11. </t>
  12. </div>
  13. </t>
  14. <t t-name="EstateCustomerListView.buttons" t-extend="ListView.buttons">
  15. <t t-jquery="button.o_list_button_add" t-operation="after">
  16. <!--btn表示按钮类
  17. 按钮颜色:btn-primary--主要按钮,btn-secondary次要按钮
  18. 按钮大小:btn-sm小按钮,btn-lg大按钮
  19. 默认按钮:btn-default-->
  20. <button type="button" class="btn btn-primary o_button_upload_estate_customer">Upload</button>
  21. </t>
  22. </t>
  23. </templates>

说明:

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" encoding="UTF-8"?>
  2. <templates>
  3. <t t-name="DataImportTestingListView.buttons" t-inherit="ListView.buttons" t-inherit-mode="primary">
  4. <xpath expr="//button[@calss='btn btn-primary o_list_button_add']" position="after">
  5. <button type="button" class="btn btn-primary o_button_upload_estate_customer">Upload</button>
  6. </xpath>
  7. </t>
  8. </templates>

发现会报错:

  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. }

最终效果

odoo 给列表视图添加按钮实现数据文件导入的更多相关文章

  1. SQLLoader5(从多个数据文件导入到同一张表)

    从多个数据文件导入到同一张表很简单,只需要在INFILE参数指定多个数据文件的路径即可.数据文件1:test1.txt1111 ALLE SALESMAN2222 WARD SALESMAN数据文件2 ...

  2. Odoo treeView列表视图详解

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10826414.html TreeView:列表视图 1:<tree>标签的属性 [tree标签内 ...

  3. SM30维护视图添加按钮

    转自http://blog.csdn.net/tsj19881202/article/details/7517232 遇到某需求,要求维护sm30的视图时,能加上排序按钮. 基本参考: http:// ...

  4. Dynamics CRM 客户端程序开发:在实体的列表界面添加按钮

    关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复114或者20140312可方便获取本文,同时可以在第一时间得到我发布的最新的博文信息,follow me! 如果没有安装Ribbon Wor ...

  5. 将csv格式的数据文件导入/导出数据库+添加新的字段

    最近一直忙于实验室的事情,没有好好更新博客,在抓包的过程中,遇到了很多问题. 因为我常用Wireshark将抓包信息导出为csv文件,这里简单mark一下将csv文件导入/导出到数据库的2种方法: 一 ...

  6. 在windows下,将mysql离线数据文件导入本地mysql数据库

    1. 查看mysql路径 SELECT @@basedir AS basePath FROM DUAL 其实mysql5.6 的数据文件在 C:\ProgramData\MySQL\MySQL Ser ...

  7. 使用 OLEDB 及 SqlBulkCopy 将多个不在同一文件夹下的 ACCESS mdb 数据文件导入MSSQL

    注:转载请标明文章原始出处及作者信息http://www.cnblogs.com/z-huifei/p/7380388.html 前言 OLE DB 是微软的战略性的通向不同的数据源的低级应用程序接口 ...

  8. sql数据文件导入数据库

    1.首先通过xshell连接数据库服务器,执行命令mysql -u root -p 命令,按照提示输入密码.连接上数据库. 2.在连接终端上执行命令create database JD_Model; ...

  9. 使用struct模块从定宽数据文件导入数据

  10. 数据文件导入mysql时出现中文乱码问题

    http://www.ynpxrz.com/n773257c2024.aspx 从shell进入mysql, mysql> show variables like ‘%char%'; +---- ...

随机推荐

  1. Linux系统安装 tftp服务 NFS服务

    安装tftp服务 安装 sudo apt-get install tftp-hpa tftpd-hpa 配置文件 # /etc/default/tftpd-hpa TFTP_USERNAME=&quo ...

  2. 第2-4-6章 springboot整合规则引擎Drools-业务规则管理系统-组件化-中台

    目录 7. Spring整合Drools 7.1 Spring简单整合Drools 7.1.1 以上代码均在drools_spring项目中 7.2 Spring整合Drools+web 7.2 以上 ...

  3. Flink SQL管理平台flink-streaming-platform-web安装搭建

    文章都在个人博客网站:https://www.ikeguang.com/ 同步,欢迎访问. 最近看到有人在用flink sql的页面管理平台,大致看了下,尝试安装使用,比原生的flink sql界面确 ...

  4. 3A锂电池充电管理芯片PW4035

    PW4052 是一颗适用于单节锂电池的.具有恒压/恒流充电模式的充电管理 IC.该芯片采用开关型的工作模式, 能够为单节锂电池提供快速. 高效且简单的充电管理解决方案. PW4052 采用三段式充电管 ...

  5. [百度营]AI studio用法提醒(自用)

    持久化安装 需要设置持久化路径: !mkdir /home/aistudio/external-libraries !pip install beautifulsoup4 -t /home/aistu ...

  6. uniapp微信小程序 原生底部导航栏

    在pages.json文件中写  "tabBar": { "color": "#333333", "selectedColor&q ...

  7. 英华学堂网课助手Linux版本

    首先我们下去GitHub把文件下载下来记得 脚本地址: https://github.com/aoaostar/mooc/releases/latest 这几个版本随便下哪个都可以,下载完之后我们通过 ...

  8. Spring+Quartz+Dom4j实现一个小项目

    目录 1.项目背景 2.技术介绍 3.实现代码 4.程序演示 5.打成jar包 1.项目背景 最近在工作中碰到了一个问题,一个叫aura的系统每天都会接收到许多xml,其中有些xml会包含错误信息,这 ...

  9. ssm——mybatis整理

    目录 1.mybatis框架概述 2.直接使用jdbc连接数据库带来的问题 3.mybatis连接池 3.1.mybatis连接池yml配置 3.2.mybatis连接池xml配置 4.一个简单的my ...

  10. Java开发网络安全常见问题

    Java开发网络安全常见问题 等闲识得东风面,万紫千红总是春 1.敏感信息明文传输 用户敏感信息如手机号.银行卡号.验证码等涉及个人隐私的敏感信息不通过任何加密直接明文传输. 如下图中小红书APP 的 ...