Skip to Content
Odoo Meniu
  • Autentificare
  • Try it free
  • Aplicații
    Finanțe
    • Contabilitate
    • Facturare
    • Cheltuieli
    • Spreadsheet (BI)
    • Documente
    • Semn
    Vânzări
    • CRM
    • Vânzări
    • POS Shop
    • POS Restaurant
    • Abonamente
    • Închiriere
    Site-uri web
    • Constructor de site-uri
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Lanț Aprovizionare
    • Inventar
    • Producție
    • PLM
    • Achiziție
    • Maintenance
    • Calitate
    Resurse Umane
    • Angajați
    • Recrutare
    • Time Off
    • Evaluări
    • Referințe
    • Flotă
    Marketing
    • Social Marketing
    • Marketing prin email
    • SMS Marketing
    • Evenimente
    • Automatizare marketing
    • Sondaje
    Servicii
    • Proiect
    • Foi de pontaj
    • Servicii de teren
    • Centru de asistență
    • Planificare
    • Programări
    Productivitate
    • Discuss
    • Aprobări
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    Aplicații Terțe Odoo Studio Platforma Odoo Cloud
  • Industrii
    Retail
    • Book Store
    • Magazin de îmbrăcăminte
    • Magazin de Mobilă
    • Magazin alimentar
    • Magazin de materiale de construcții
    • Magazin de jucării
    Food & Hospitality
    • Bar and Pub
    • Restaurant
    • Fast Food
    • Guest House
    • Distribuitor de băuturi
    • Hotel
    Proprietate imobiliara
    • Real Estate Agency
    • Firmă de Arhitectură
    • Construcție
    • Estate Managament
    • Grădinărit
    • Asociația Proprietarilor de Proprietăți
    Consultanta
    • Firma de Contabilitate
    • Partener Odoo
    • Agenție de marketing
    • Law firm
    • Atragere de talente
    • Audit & Certification
    Producție
    • Textil
    • Metal
    • Mobilier
    • Mâncare
    • Brewery
    • Cadouri corporate
    Health & Fitness
    • Club Sportiv
    • Magazin de ochelari
    • Centru de Fitness
    • Wellness Practitioners
    • Farmacie
    • Salon de coafură
    Trades
    • Handyman
    • IT Hardware and Support
    • Asigurare socială de stat
    • Cizmar
    • Servicii de curățenie
    • HVAC Services
    Altele
    • Organizație nonprofit
    • Agenție de Mediu
    • Închiriere panouri publicitare
    • Fotografie
    • Închiriere biciclete
    • Asigurare socială
    Browse all Industries
  • Comunitate
    Învăță
    • Tutorials
    • Documentație
    • Certificări
    • Instruire
    • Blog
    • Podcast
    Empower Education
    • Program Educațional
    • Scale Up! Business Game
    • Visit Odoo
    Obține Software-ul
    • Descărcare
    • Compară Edițiile
    • Lansări
    Colaborați
    • Github
    • Forum
    • Evenimente
    • Translations
    • Devino Partener
    • Services for Partners
    • Înregistrează-ți Firma de Contabilitate
    Obține Servicii
    • Găsește un Partener
    • Găsiți un contabil
    • Meet an advisor
    • Servicii de Implementare
    • Referințe ale clienților
    • Suport
    • Actualizări
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Obține un demo
  • Prețuri
  • Ajutor

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

  • CRM
  • e-Commerce
  • Contabilitate
  • Inventar
  • PoS
  • Proiect
  • MRP
All apps
Trebuie să fiți înregistrat pentru a interacționa cu comunitatea.
All Posts Oameni Insigne
Etichete (View all)
odoo accounting v14 pos v15
Despre acest forum
Trebuie să fiți înregistrat pentru a interacționa cu comunitatea.
All Posts Oameni Insigne
Etichete (View all)
odoo accounting v14 pos v15
Despre acest forum
Suport

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

Abonare

Primiți o notificare când există activitate la acestă postare

Această întrebare a fost marcată
2 Răspunsuri
5952 Vizualizări
Imagine profil
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
Imagine profil
Abandonează
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

Imagine profil
Zbik
Cel mai bun răspuns

@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
Imagine profil
Abandonează
Pascal Tremblay
Autor

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

Imagine profil
Pascal Tremblay
Autor Cel mai bun răspuns

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
Imagine profil
Abandonează
Enjoying the discussion? Don't just read, join in!

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

Înscrie-te
Comunitate
  • Tutorials
  • Documentație
  • Forum
Open Source
  • Descărcare
  • Github
  • Runbot
  • Translations
Servicii
  • Hosting Odoo.sh
  • Suport
  • Actualizare
  • Custom Developments
  • Educație
  • Găsiți un contabil
  • Găsește un Partener
  • Devino Partener
Despre Noi
  • Compania noastră
  • Active de marcă
  • Contactați-ne
  • Locuri de muncă
  • Evenimente
  • Podcast
  • Blog
  • Clienți
  • Aspecte juridice • Confidențialitate
  • Securitate
الْعَرَبيّة 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 este o suită de aplicații de afaceri open source care acoperă toate nevoile companiei dvs.: CRM, comerț electronic, contabilitate, inventar, punct de vânzare, management de proiect etc.

Propunerea de valoare unică a Odoo este să fie în același timp foarte ușor de utilizat și complet integrat.

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