Pular para o conteúdo
Odoo Menu
  • Entrar
  • Experimente grátis
  • Aplicativos
    Finanças
    • Financeiro
    • Faturamento
    • Despesas
    • Planilhas (BI)
    • Documentos
    • Assinar Documentos
    Vendas
    • CRM
    • Vendas
    • PDV Loja
    • PDV Restaurantes
    • Assinaturas
    • Locação
    Websites
    • Criador de Sites
    • e-Commerce
    • Blog
    • Fórum
    • Chat ao Vivo
    • e-Learning
    Cadeia de mantimentos
    • Inventário
    • Fabricação
    • PLM - Ciclo de Vida do Produto
    • Compras
    • Manutenção
    • Qualidade
    Recursos Humanos
    • Funcionários
    • Recrutamento
    • Folgas
    • Avaliações
    • Indicações
    • Frota
    Marketing
    • Redes Sociais
    • Marketing por E-mail
    • Marketing por SMS
    • Eventos
    • Automação de Marketing
    • Pesquisas
    Serviços
    • Projeto
    • Planilhas de Horas
    • Serviço de Campo
    • Central de Ajuda
    • Planejamento
    • Compromissos
    Produtividade
    • Mensagens
    • Aprovações
    • Internet das Coisas
    • VoIP
    • Conhecimento
    • WhatsApp
    Aplicativos de terceiros Odoo Studio Plataforma Odoo Cloud
  • Setores
    Varejo
    • Loja de livros
    • Loja de roupas
    • Loja de móveis
    • Mercearia
    • Loja de ferramentas
    • Loja de brinquedos
    Comida e hospitalidade
    • Bar e Pub
    • Restaurante
    • Fast Food
    • Hospedagem
    • Distribuidor de bebidas
    • Hotel
    Imóveis
    • Imobiliária
    • Escritório de arquitetura
    • Construção
    • Administração de propriedades
    • Jardinagem
    • Associação de proprietários de imóveis
    Consultoria
    • Escritório de Contabilidade
    • Parceiro Odoo
    • Agência de marketing
    • Escritório de advocacia
    • Aquisição de talentos
    • Auditoria e Certificação
    Fabricação
    • Têxtil
    • Metal
    • Móveis
    • Alimentação
    • Cervejaria
    • Presentes corporativos
    Saúde e Boa forma
    • Clube esportivo
    • Loja de óculos
    • Academia
    • Profissionais de bem-estar
    • Farmácia
    • Salão de cabeleireiro
    Comércio
    • Handyman
    • Hardware e Suporte de TI
    • Sistemas de energia solar
    • Sapataria
    • Serviços de limpeza
    • Serviços de climatização
    Outros
    • Organização sem fins lucrativos
    • Agência Ambiental
    • Aluguel de outdoors
    • Fotografia
    • Aluguel de bicicletas
    • Revendedor de software
    Navegar por todos os setores
  • Comunidade
    Aprenda
    • Tutoriais
    • Documentação
    • Certificações
    • Treinamento
    • Blog
    • Podcast
    Empodere a Educação
    • Programa de educação
    • Scale Up! Jogo de Negócios
    • Visite a Odoo
    Obtenha o Software
    • Baixar
    • Comparar edições
    • Releases
    Colaborar
    • Github
    • Fórum
    • Eventos
    • Traduções
    • Torne-se um parceiro
    • Serviços para parceiros
    • Cadastre seu escritório contábil
    Obtenha os serviços
    • Encontre um parceiro
    • Encontre um Contador
    • Conheça um consultor
    • Serviços de Implementação
    • Referências de Clientes
    • Suporte
    • Upgrades
    Github YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Faça uma demonstração
  • Preços
  • Ajuda

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

  • CRM
  • e-Commerce
  • Financeiro
  • Inventário
  • PoS
  • Projeto
  • MRP
All apps
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
Ajuda

Issue with a new Product Label Template (102x102) in Odoo V17

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
developmentpythonqweb
1763 Visualizações
Avatar
Quentin Roland

Hi everyone,

I’m encountering an issue with a custom product label template I created in Odoo based on the standard implementation. The template is supposed to display products with specific dimensions (102x102), but the following problems occur:

  1. No products are displayed at all: The table seems empty, and none of the data I’m passing appears to render correctly.
  2. H1 tag stops iterating: Inside the loop for testing, the <h1> tags only display up to the third iteration and do not proceed further.

Here’s the relevant portion of my code:


<?xml version="1.0" encoding="UTF-8"?>

<odoo>

<data>

<!-- Template principal -->

<template id="template_producttemplatelabel102x102">

<t t-call="web.basic_layout">

<div class="page">

<t t-set="columns" t-value="102"/>

<t t-set="rows" t-value="102"/>

<t t-call="happy_rabbits_custo.report_productlabel_102x102"/>

<t t-log="quantity"/>

<t t-log="current_data"/>

<t t-log="product"/>

<t t-log="barcode"/>


</div>

</t>

</template>


<!-- Template de gestion des labels -->

<template id="report_productlabel_102x102">

<t t-call="web.html_container">

<t t-esc='columns'/>

<t t-esc='rows'/>

<t t-if="columns and rows">

<t t-if="columns == 102 and rows == 102">

<t t-set="padding_page" t-value="'padding: 0mm'"/>

<t t-set="report_to_call" t-value="'102x102'"/>

</t>

<t t-set="page_numbers" t-value="1"/>

<h1>lalalallalalaal3 </h1>

<t t-foreach="range(page_numbers)" t-as="page">

<h1>lalalallalalaal3 </h1>


<div class="o_label_sheet" t-att-style="padding_page">

<table class="my-0 table table-sm table-borderless">

<t t-foreach="range(rows)" t-as="row">

<tr>

<t t-foreach="range(columns)" t-as="column">

<t t-if="not current_quantity and quantity and not (current_data and current_data[1])">

<h1>lalalallalalaal5 </h1>

<t t-set="current_data" t-value="quantity.popitem()"/>

<t t-set="product" t-value="current_data[0]"/>

<h1>lalalallalalaal6 </h1>


<t t-set="barcode_and_qty" t-value="current_data[1].pop()"/>

<t t-set="barcode" t-value="barcode_and_qty[0]"/>

<t t-set="current_quantity" t-value="barcode_and_qty[1]"/>

</t>

<t t-if="current_quantity">

<t t-set="make_invisible" t-value="False"/>

<t t-set="current_quantity" t-value="current_quantity - 1"/>

</t>

<t t-else="">

<t t-set="make_invisible" t-value="True"/>

</t>

</t>

<t t-if="report_to_call == '102x102'">

<t t-call="happy_rabbits_custo.report_simple_label102x102"/>

</t>

</tr>

</t>

</table>

</div>

</t>

</t>

</t>

</template>


<template id="report_simple_label102x102">

<t t-set="barcode_size" t-value="'width:80mm;height:80mm'"/>

<t t-set="table_style" t-value="'width:102mm;height:102mm;'"/>

<td t-att-style="make_invisible and 'visibility:hidden;'">

<div class="o_label_full" t-att-style="table_style">

<div class="o_label_name">

<t t-if="quantity">

<p>Quantity: <t t-esc="quantity"/></p>

</t>

<t t-if="product">

<p>Product: <t t-esc="product.display_name"/></p>

</t>

<t t-else="">

<p>No product data available.</p>

</t>


</div>

</div>

</td>

</template>


<record id="happy_rabbits_custo.report_product_template_label_102x102" model="ir.actions.report">

<field name="name">Product Label 102x102</field>

<field name="model">product.template</field>

<field name="report_type">qweb-pdf</field>

<field name="report_name">happy_rabbits_custo.template_producttemplatelabel102x102</field>

<field name="report_file">happy_rabbits_custo.template_producttemplatelabel102x102</field>

<field name="print_report_name">'Products Labels - %s' % (object.name)</field>

</record>


</data>

</odoo>

And the python model : 

from odoo import models, fields

import logging


_logger = logging.getLogger(__name__)


class ProductLabelLayout(models.TransientModel):

_inherit = 'product.label.layout'


print_format = fields.Selection(

selection_add=[('102x102xprice', '102x102')],

ondelete={'102x102xprice': 'set default'}, # Définir une politique pour la valeur ajoutée

)


def _prepare_report_data(self):

xml_id, data = super()._prepare_report_data()

if self.print_format in ['102x102xprice']:

if 'product.' in xml_id:

xml_id = xml_id.replace('product.', 'happy_rabbits_custo.')

active_model = ''

if self.product_tmpl_ids:

products = self.product_tmpl_ids.ids

active_model = 'product.template'

_logger.info('products: %s', products)

elif self.product_ids:

products = self.product_ids.ids

active_model = 'product.product'

_logger.info('products: %s', products)

else:

raise UserError(_("No product to print, if the product is archived please unarchive it before printing its label."))


_logger.info('products: %s', products)

data.update({

'active_model': active_model,

'quantity_by_product': {p: self.custom_quantity for p in products},

'layout_wizard': self.id,

'price_included': 'xprice' in self.print_format,

})



return xml_id, data



def _prepare_data(env, docids, data):

_logger.info("Starting _prepare_data with data: %s", data)


layout_wizard = env['product.label.layout'].browse(data.get('layout_wizard'))

if not layout_wizard:

_logger.error("Layout wizard is missing.")

return {}


if layout_wizard.print_format == '102x102xprice':

quantity = data.get('quantity_by_product', {})

_logger.info("Quantity by Product: %s", quantity)


if not quantity:

_logger.error("Quantity by product is empty.")

return {}


total = sum(quantity.values())

rows = layout_wizard.rows or 1

columns = layout_wizard.columns or 1

page_numbers = (total - 1) // (rows * columns) + 1


products = env['product.template'].browse(list(quantity.keys()))

_logger.info("Products loaded: %s", products)


return {

'quantity': {p.id: quantity[str(p.id)] for p in products}, # Correct format

'page_numbers': page_numbers,

'price_included': data.get('price_included'),

'extra_html': layout_wizard.extra_html,

'pricelist': layout_wizard.pricelist_id,

}



class ReportHappyRabbitsProductTemplateLabel102x102(models.AbstractModel):

_name = 'report.happy_rabbits_custo.report_producttemplatelabel102x102'

_description = 'Product Label Report 102x102'


def _get_report_values(self, docids, data):

return ProductLabelLayout._prepare_data(self.env, docids, data)


Questions:

  1. Why might the data not display in the template like my products name or other? Could there be an issue with the t-set assignments?

Any insights or suggestions would be greatly appreciated! Thanks in advance for your help.

0
Avatar
Cancelar
Está gostando da discussão? Não fique apenas lendo, participe!

Crie uma conta hoje mesmo para aproveitar os recursos exclusivos e interagir com nossa incrível comunidade!

Inscreva-se
Publicações relacionadas Respostas Visualizações Atividade
TypeError str and datetime Resolvido
development python
Avatar
Avatar
Avatar
2
ago. 24
2298
Duplicate Orders in POS When Clicking Order Button (Odoo 18)
development python Point Of Sale
Avatar
Avatar
2
fev. 25
2407
Email template - list of followers
python qweb email
Avatar
Avatar
Avatar
2
jun. 23
3169
Best practices for code reuse in Odoo addon development ?
development python methodology
Avatar
Avatar
1
abr. 23
6074
My custom report is changing when user Configured the Document Layout Resolvido
python qweb v14
Avatar
Avatar
1
jan. 23
3347
Comunidade
  • Tutoriais
  • Documentação
  • Fórum
Open Source
  • Baixar
  • Github
  • Runbot
  • Traduções
Serviços
  • Odoo.sh Hosting
  • Suporte
  • Upgrade
  • Desenvolvimentos personalizados
  • Educação
  • Encontre um Contador
  • Encontre um parceiro
  • Torne-se um parceiro
Sobre nós
  • Nossa empresa
  • Ativos da marca
  • Contato
  • Empregos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidade
  • Segurança
الْعَرَبيّة 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 é um conjunto de aplicativos de negócios em código aberto que cobre todas as necessidades de sua empresa: CRM, comércio eletrônico, contabilidade, estoque, ponto de venda, gerenciamento de projetos, etc.

A proposta de valor exclusiva Odoo é ser, ao mesmo tempo, muito fácil de usar e totalmente integrado.

Site feito com

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