跳至内容
Odoo 菜单
  • 登录
  • 免费试用
  • 应用程序
    财务
    • 会计
    • 发票
    • 费用
    • 电子表格 (BI)
    • 文档
    • 电子签名
    销售
    • 客户关系管理
    • 销售
    • POS 销售点管理-零售
    • POS 销售点管理 - 餐厅
    • 订阅
    • 租赁
    网站
    • 网站设计
    • 电子商务
    • 博客
    • 论坛
    • 在线客服
    • 在线学习
    供应链
    • 库存
    • 制造
    • 产品生命周期
    • 采购
    • 维护保养
    • 品控
    人力资源
    • 员工
    • 招聘
    • 休假
    • 评价
    • 内部推荐
    • 车队
    营销
    • 社媒营销
    • 电邮营销
    • 短信营销
    • 近期活动
    • 营销自动化
    • 网上调查
    服务
    • 项目管理
    • 工时单
    • 现场服务
    • 服务台
    • 排期
    • 预约
    生产力
    • 讨论
    • 批核
    • IoT物联网
    • VoIP
    • 知识库
    • WhatsApp
    第三方应用软件 Odoo 定制 Odoo云端平台
  • 行业
    零售
    • 书店
    • 服装店
    • 家具店
    • 食品杂货店
    • 五金店
    • 玩具店
    餐饮与酒店服务
    • 酒吧及酒馆
    • 餐厅
    • 快餐
    • 民宿
    • 饮品分销商
    • 酒店
    房地产
    • 房地产代理
    • 建筑师事务所
    • 建造业
    • 地产管理
    • 园艺
    • 业主协会
    咨询
    • 会计师事务所
    • Odoo合作伙伴
    • 市场推广公司
    • 律师事务所
    • 人才招聘
    • 审核 & 认证
    制造
    • 纺织
    • 金属
    • 家具
    • 食品
    • 啤酒厂
    • 企业礼品
    保健与健身
    • 体育俱乐部
    • 眼镜店
    • 健身中心
    • 健康从业者
    • 药房
    • 发型屋
    商贸服务
    • 维修人员
    • IT 硬件及支持
    • 太阳能系统
    • 鞋匠
    • 清洁服务
    • 暖通空调服务
    其他
    • 非营利组织
    • 环境机构
    • 广告牌租赁
    • 摄影服务
    • 自行车租赁
    • 软件经销商
    浏览所有行业
  • 社区
    学习
    • 教学视频
    • 文档
    • 认证
    • 培训
    • 博客
    • 播客
    赋能教育
    • 教育计划
    • Scale Up! 商业游戏
    • 参观Odoo
    获取软件
    • 下载
    • 版本对比
    • 发布
    合作
    • Github
    • 论坛
    • 近期活动
    • 翻译
    • 成为合作伙伴
    • 合作伙伴服务
    • 注册您的会计事务所
    获取服务
    • 寻找合作伙伴
    • 查找会计服务
    • 预约顾问咨询
    • 安装及推行服务
    • 客户参考
    • 支持
    • 升级
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    获取演示
  • 定价
  • 技术支持

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • 客户关系管理
  • e-Commerce
  • 会计
  • 库存
  • PoS
  • 项目
  • MRP
All apps
只限注册用戶才可与社群互动。
所有帖文 人 徽章
标签 (查看所有)
odoo accounting v14 pos v15
关于此论坛区
只限注册用戶才可与社群互动。
所有帖文 人 徽章
标签 (查看所有)
odoo accounting v14 pos v15
关于此论坛区
帮助

How to pass a value from a class to an other class?

订阅

此帖文有活动时,接收通知

此问题已终结
2 回复
5946 查看
形象
Pascal Tremblay

Hello all of you,

I would need to understand a new concept...

See example first class :

class report_saleslines_pt(models.AbstractModel):

    _name = 'report.point_of_sale.report_saleslines'
    _template = 'point_of_sale.report_saleslines'

    @api.multi
    def render_html(self, data=None):
       report.choosen_paper = a_number_or_object
 

We have a second class.

class Report(osv.Model):
    _inherit = "report"
    _name = "report"
    _description = "Report"

    @api.v7
    def get_pdf(self, cr, uid, ids, report_name, html=None, data=None, context=None):
        paper = report.choosen_paper

 

Our two classes work well and are well declared (I didn't paste all the code).

How could I give a value to report.choosen_paper in the class report_saleslines_pt and after recup this value in get_pdf() from the class report?

How to exchange temp value beetqween classes?

Do you understand what I mean?

Thanks for words or idea.

 

FIRST UPDATE ::::

See example first class :

class report_saleslines_pt(models.AbstractModel):

    _name = 'report.point_of_sale.report_saleslines'
    _template = 'point_of_sale.report_saleslines'

    @api.multi
    def render_html(self, data=None):
        self.env['report'].with_context(exchangeVAR='KILLINGDESTROY')

 

We have a second class.

class Report(osv.Model):
    _inherit = "report"
    _name = "report"
    _description = "Report"

    @api.v7
    def get_pdf(self, cr, uid, ids, report_name, html=None, data=None, context=None):  

         _logger.error("REPORT_LAPAGEPT :: %s %s", 'CONTEXT :: ', context)

I can now see the context in my log. But still NO trace of exchangeVAR in the context.

Thanks

0
形象
丢弃
Pascal Tremblay
编写者

I don't want to change any value in the database. I just want a kind of global value.

Zbik

pass with context?

Pascal Tremblay
编写者

I have printed this : https://www.odoo.com/fr_FR/forum/help-1/question/whats-the-context-2236 Trying it. Thanks

Pascal Tremblay
编写者

Not able to modify context in render_html. ANd make this context the same than in get_pdf

形象
Zbik
最佳答案

@Pascal, see how works get_pdf(). In first step (on begining) call self.get_html(). In get_html() I see ... return particularreport_obj.render_html() ... render_html() you inherit... context propagates in the opposite direction

1
形象
丢弃
Pascal Tremblay
编写者

Thanks A LOT!!!!! Again! I have learned many important concepts. I will publish my code soon.

形象
Pascal Tremblay
编写者 最佳答案

FIRST CLASS

from openerp import api
from openerp import SUPERUSER_ID
from openerp.exceptions import AccessError
from openerp.osv import osv
from openerp.tools import config
from openerp.tools.misc import find_in_path
from openerp.tools.translate import _
from openerp.addons.web.http import request
from openerp.tools.safe_eval import safe_eval as eval

import re
import time
import base64
import logging
import tempfile
import lxml.html
import os
import subprocess
from contextlib import closing
from distutils.version import LooseVersion
from functools import partial
from pyPdf import PdfFileWriter, PdfFileReader


import logging
_logger = logging.getLogger(__name__)


class Report(osv.Model):
    _inherit = "report"
    _name = "report"
    _description = "Report"

    def whichCompanyPrefix(self):
        self.cr, self.uid, self.pool = request.cr, request.uid, request.registry
        user = self.pool["res.users"].browse(self.cr, self.uid, self.uid)
    
        company_id = user.company_id.id
        #_logger.error('ID = ' + str(company_id))
        company_name = user.company_id.name
        #_logger.error('NAME = ' + company_name)
        company_prefix = user.company_id.x_company_prefix
        
        if not company_prefix :
 
            company_prefix = 'ZZ'
        
        _logger.error('REPORT_LAPAGEPT :: PREFIX = ' + company_prefix)
        
        return company_prefix
    
    
    
    def choosePaper(self, report, user):
        _logger.error('REPORT_LAPAGEPT :: CHOOSEPAPER : ')

        modelll = report.model
        #Tous les rapports dans le point de vente.
        if modelll == 'pos.order':
            cie_pos_paperformat = user.company_id.x_pos_paperformat
            
            if cie_pos_paperformat:
                paperformat = cie_pos_paperformat
                _logger.error('REPORT_LAPAGEPT :: PAPIER POS DE LA COMPAGNIE : ' + str(paperformat))
            elif report.paperformat_id:
                paperformat = report.paperformat_id
                _logger.error('REPORT_LAPAGEPT :: PAPIER DU REPORT : ' + str(paperformat))
            else:
                ref = partial(self.pool['ir.model.data'].xmlid_to_res_id, cr, SUPERUSER_ID)
                ref_id = ref('report.paperformat_us')
                paperformat = self.pool['report.paperformat'].browse(cr, SUPERUSER_ID, ref_id, context=context)
                
                _logger.error('REPORT_LAPAGEPT :: PAPIER PAR DEFAUT LETTER : ' + str(paperformat))
        
        #Tous les rapports hors du menu point de vente.
        else:
            cie_paperformat = user.company_id.paperformat_id
            
            if cie_paperformat:
                paperformat = user.company_id.paperformat_id
            else:
                paperformat = report.paperformat_id
    

        return paperformat
    
    @api.v7
    def get_html(self, cr, uid, ids, report_name, data=None, context=None):
        """This method generates and returns html version of a report.
        """
        # If the report is using a custom model to render its html, we must use it.
        # Otherwise, fallback on the generic html rendering.
        _logger.error('REPORT_LAPAGEPT :: GET_HTML ' + str(report_name))
        
        report = self._get_report_from_name(cr, uid, report_name)

        user = self.pool['res.users'].browse(cr, uid, uid)
        
        chosenPaper = Report.choosePaper(self, report, user)
        
        _logger.error('REPORT_LAPAGEPT :: GET_PDF : CHOSENPAPER ' + str(chosenPaper))
        
        context.update({'chosenPaper':chosenPaper})
        
        try:
            report_model_name = 'report.%s' % report_name
            particularreport_obj = self.pool[report_model_name]
            return particularreport_obj.render_html(cr, uid, ids, data=data, context=context)
        except KeyError:
            report = self._get_report_from_name(cr, uid, report_name)
            report_obj = self.pool[report.model]
            docs = report_obj.browse(cr, uid, ids, context=context)
            docargs = {
                'doc_ids': ids,
                'doc_model': report.model,
                'docs': docs,
            }
            return self.render(cr, uid, [], report.report_name, docargs, context=context)

    @api.v7
    def get_pdf(self, cr, uid, ids, report_name, html=None, data=None, context=None):
        """This method generates and returns pdf version of a report.
        """
        _logger.error('REPORT_LAPAGEPT :: GET_PDF BEGIN' + str(report_name))

        if context is None:
            context = {}

        if html is None:
            html = self.get_html(cr, uid, ids, report_name, data=data, context=context)

        html = html.decode('utf-8')  # Ensure the current document is utf-8 encoded.

        # Get the ir.actions.report.xml record we are working on.
        report = self._get_report_from_name(cr, uid, report_name)

        # Check if we have to save the report or if we have to get one from the db.
        save_in_attachment = self._check_attachment_use(cr, uid, ids, report)

        paperformat = context.get('chosenPaper')

        # Preparing the minimal html pages
        css = ''  # Will contain local css
        headerhtml = []
        contenthtml = []
        footerhtml = []
        irconfig_obj = self.pool['ir.config_parameter']
        base_url = irconfig_obj.get_param(cr, SUPERUSER_ID, 'report.url') or irconfig_obj.get_param(cr, SUPERUSER_ID, 'web.base.url')

        # Minimal page renderer
        view_obj = self.pool['ir.ui.view']
        render_minimal = partial(view_obj.render, cr, uid, 'report.minimal_layout', context=context)

        # The received html report must be simplified. We convert it in a xml tree
        # in order to extract headers, bodies and footers.
        try:
            root = lxml.html.fromstring(html)
            match_klass = "//div[contains(concat(' ', normalize-space(@class), ' '), ' {} ')]"

            for node in root.xpath("//html/head/style"):
                css += node.text

            for node in root.xpath(match_klass.format('header')):
                body = lxml.html.tostring(node)
                header = render_minimal(dict(css=css, subst=True, body=body, base_url=base_url))
                headerhtml.append(header)

            for node in root.xpath(match_klass.format('footer')):
                body = lxml.html.tostring(node)
                footer = render_minimal(dict(css=css, subst=True, body=body, base_url=base_url))
                footerhtml.append(footer)

            for node in root.xpath(match_klass.format('page')):
                # Previously, we marked some reports to be saved in attachment via their ids, so we
                # must set a relation between report ids and report's content. We use the QWeb
                # branding in order to do so: searching after a node having a data-oe-model
                # attribute with the value of the current report model and read its oe-id attribute
                if ids and len(ids) == 1:
                    reportid = ids[0]
                else:
                    oemodelnode = node.find(".//*[@data-oe-model='%s']" % report.model)
                    if oemodelnode is not None:
                        reportid = oemodelnode.get('data-oe-id')
                        if reportid:
                            reportid = int(reportid)
                    else:
                        reportid = False

                # Extract the body
                body = lxml.html.tostring(node)
                reportcontent = render_minimal(dict(css=css, subst=False, body=body, base_url=base_url))

                contenthtml.append(tuple([reportid, reportcontent]))

        except lxml.etree.XMLSyntaxError:
            contenthtml = []
            contenthtml.append(html)
            save_in_attachment = {}  # Don't save this potentially malformed document

        # Get paperformat arguments set in the root html tag. They are prioritized over
        # paperformat-record arguments.
        specific_paperformat_args = {}
        for attribute in root.items():
            if attribute[0].startswith('data-report-'):
                specific_paperformat_args[attribute[0]] = attribute[1]


        _logger.error('REPORT_LAPAGEPT :: GET_PDF END' + str(report_name))

        # Run wkhtmltopdf process
        return self._run_wkhtmltopdf(
            cr, uid, headerhtml, footerhtml, contenthtml, context.get('landscape'),
            paperformat, specific_paperformat_args, save_in_attachment
        )

 

SECOND CLASS

import logging
_logger = logging.getLogger(__name__)
from openerp import api, models

class report_saleslines_pt(models.AbstractModel):
    _name = 'report.point_of_sale.report_saleslines'
    _template = 'point_of_sale.report_saleslines'

    @api.multi
    def render_html(self, data=None):

        report_obj = self.env['report']
        report = report_obj._get_report_from_name('point_of_sale.report_saleslines')
        context2 = self.env.context
        
        _logger.error("REPORT_SALELINES_PT :: RENDER_HTML :: %s %s", 'CONTEXT :: ', context2)
        
        paperformat_obj = context2.get('chosenPaper')
        
        _logger.error("REPORT_SALELINES_PT :: RENDER_HTML :: %s %s", 'CHOSENPAPER :: ', paperformat_obj)
        
        docargs = {
            'paperformat': paperformat_obj,
            'doc_ids': self._ids,
            'doc_model': report.model,
            'docs': self,
        }
        return report_obj.render('point_of_sale.report_saleslines', docargs)

report_saleslines_pt()

 

0
形象
丢弃
喜欢讨论吗?不要只阅读,加入进来!

立即创建账户,享受专属功能,与我们的精彩社区互动!

注册
社区
  • 教学视频
  • 文档
  • 论坛
开源
  • 下载
  • Github
  • Runbot
  • 翻译
服务
  • Odoo.sh 托管
  • 支持
  • 升级
  • 自定义开发服务
  • 教育
  • 查找会计服务
  • 寻找合作伙伴
  • 成为合作伙伴
关于我们
  • 我们的公司
  • 品牌资产
  • 联系我们
  • 招聘
  • 近期活动
  • 播客
  • 博客
  • 客户
  • 法律 • 隐私
  • 安全
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo致力于为企业管理提供高效智能的开源解决方案,是全球业内高速成长的软件服务商之一,逾七百五十万用户选择Odoo进行数字化升级。通过一系列全业务链覆盖、高度集成、简单易用的商业应用,助力企业实现信息化改革、降本增效并释放公司增长潜力。

Odoo独特的价值在于是一款非常容易使用又完全集成的应用。

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now