Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

compute field not working properly

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
pythonmodelcomputetechnical
2 Respuestas
5238 Vistas
Avatar
Sagar Shah

Hi have a Image field setup for compute, and it depends on 2 fields, however I noticed when one of the 2 fields is edited it triggers compute but doesn't pass the value of other field properly and hence the compute logic fails, wanted to know if this is a known issue?


from odoo import api, models, fields
from PIL import Image
import io
import base64
import qrcode
import lnurl

class custom_info(models.Model):

_inherit = 'hr.employee'
employee_ln_address = fields.Char(string="Employee lightning address : ", required=False)
employee_ln_qr_image = fields.Image(compute="_compute_ln_qr_image",string="Employee lightning QR code")


@api.depends('image_1920','employee_ln_address')
def _compute_ln_qr_image(self):
    ​for record in self:
        record.employee_ln_qr_image=False
        if record.image_1920:
            logo = Image.open(io.BytesIO(base64.b64decode(record.image_1920)))
            basewidth = 200
            wpercent = (basewidth/float(logo.size[0]))
            hsize = int((float(logo.size[1])*float(wpercent)))
            logo = logo.resize((basewidth, hsize), Image.ANTIALIAS)
            QRcode =qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H)
            if record.employee_ln_address:
                lnusr,lndomain = record.employee_ln_address.split('@')
                qrmessage = 'lightning:'+lnurl.encode('https://'+lndomain+'/.well-known/lnurlp/'+lnusr)
                QRcode.add_data(qrmessage)
                QRcode.make()
                QRcolor = 'Black'
                QRimg = QRcode.make_image(fill_color=QRcolor, back_color="white").convert('RGB')# adding color to QR code
                pos = ((QRimg.size[0] - logo.size[0]) // 2,(QRimg.size[1] - logo.size[1]) // 2)
                QRimg.paste(logo, pos)
                QRinMem = io.BytesIO()
                QRimg.save(QRinMem,"JPEG")
                QRinMem.seek(0)
                  record.employee_ln_qr_image=base64.b64encode(QRinMem.read())

0
Avatar
Descartar
Ray Carnes (ray)

I would post the code for "logic for compute" to give people more clues.

Sagar Shah
Autor

have updated the full code for compute now

Avatar
Jort de Vreeze
Mejor respuesta

I have done something similar for a project where I created QR codes to be printed by a label printer. What worked for me was the following:

Change the field from field.Image(compute='_compute_ln_qr_image')​ to field.Binary(compute='_compute_ln_qr_image')​

The remainder of your code is similar like for my project code. Try to add logging (e.g., _logger.info(Image Size:{QRimg.size}')​ so you can check whether the QR code generated is a valid image.

In your view you should use the image widget:

[field name="employee_ln_qr_image" widget="image" readonly="True"/]

I hope this helps!

0
Avatar
Descartar
Sagar Shah
Autor

Thanks tried it but didn't work. The problem is one of the fields that the QR field depends on is a image field, I'm trying to embed the employee Avatar in the QR code, and that seems to be the problem. If I edit the Avatar and it trigger compute it works fine, but if I edit the other field on which the compute is dependent it tirggers compute method but for some reason doesn't pass the value of the other image field that it depends on

Avatar
shubham shiroya
Mejor respuesta

try this way:

you can use the @api.onchange decorator instead of @api.depends to trigger the compute method when the employee_ln_address field is modified. The @api.onchange decorator ensures that the compute method receives the correct value of the modified field.

@api.onchange('employee_ln_address')
def _onchange_employee_ln_address(self):
for record in self:
record.employee_ln_qr_image = False
if record.image_1920:
# Your compute logic goes here
# ...

By using the @api.onchange decorator, the _onchange_employee_ln_address method will be triggered whenever the employee_ln_address field is modified, ensuring that the compute logic receives the correct value.

Make sure to remove the @api.depends decorator from the _compute_ln_qr_image method.

0
Avatar
Descartar
Sagar Shah
Autor

Thanks, i tried onchange as well but same behavior, I am not sure but something specific to image fields, other fields i don't see any issue

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
How to get a person's age from his date of birth in Odoo? Resuelto
python compute
Avatar
Avatar
Avatar
2
may 20
6843
What is active_id? Resuelto
python technical
Avatar
Avatar
Avatar
2
ene 24
13817
Loading a Model Object with data loaded from an API
python model
Avatar
Avatar
1
mar 15
8991
v16: why Odoo raise this error - compute to get Length Resuelto
model compute odoo16features
Avatar
Avatar
2
oct 23
4602
How product lines comes in sale order lines when you validate a delivery order directly from delivery?
python technical v14
Avatar
0
may 21
2106
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

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