Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

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

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

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

Subscriure's

Get notified when there's activity on this post

This question has been flagged
2 Respostes
5939 Vistes
Avatar
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
Avatar
Descartar
Pascal Tremblay
Autor

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
Autor

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

Pascal Tremblay
Autor

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

Avatar
Zbik
Best Answer

@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
Avatar
Descartar
Pascal Tremblay
Autor

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

Avatar
Pascal Tremblay
Autor Best Answer

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
Avatar
Descartar
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة 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 és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

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