Odoo Help

Welcome!

This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.

0

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

By
Pascal Tremblay
on 2/26/15, 2:44 PM 868 views

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

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

Pascal Tremblay
on 2/26/15, 2:53 PM

pass with context?

zbik
on 2/26/15, 3:13 PM

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

Pascal Tremblay
on 2/26/15, 3:51 PM

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

Pascal Tremblay
on 2/26/15, 8:16 PM
1

zbik

--zbik--
5941
| 6 4 7
Lodz, Poland
--zbik--


zbik
On 2/27/15, 8:06 PM

@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

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

Pascal Tremblay
on 2/27/15, 8:07 PM
0

Pascal Tremblay

--Pascal Tremblay--
1312
| 5 2 7
Alma, Canada
--Pascal Tremblay--


Pascal Tremblay
On 2/27/15, 8:11 PM

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()

 

Your Answer

Please try to give a substantial answer. If you wanted to comment on the question or answer, just use the commenting tool. Please remember that you can always revise your answers - no need to answer the same question twice. Also, please don't forget to vote - it really helps to select the best questions and answers!

About This Community

This community is for professionals and enthusiasts of our products and services. Read Guidelines

Question tools

2 follower(s)

Stats

Asked: 2/26/15, 2:44 PM
Seen: 868 times
Last updated: 3/16/15, 8:10 AM