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

Run server action only on certain products

Suscribirse

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

Se marcó esta pregunta
actionserverroutes
2 Respuestas
3218 Vistas
Avatar
Aleksander Steffensen

Hello

I am trying to add a server action / contextual action to generate an internal reference for my manufactured products that do not have an internal reference already. The Python code that is executed looks like this:

for record in records:
  if record['route_ids' == 6]:
    if not record['default_code']:
      record['default_code'] = env['ir.sequence'].next_by_code('manufactured_product.default_code')
  else:
    raise UserError(_("Product is not manufactured."))

I've checked that the "Manufacture" route has ID 6. I want Odoo to only allow generation of internal reference for manufactured products. The problem is that if I try to run this server action on products that are not manufactured (only "Buy" route), the action still runs and generates an internal reference.

I'm obviously doing something wrong here. Anyone with a sharp eye who can see what's wrong with my code?

0
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta

Hi,

Maybe the issue in your code is with the way you are checking if the product is manufactured or not. The condition if record['route_ids' == 6]: is not correct. You are trying to compare the 'route_ids' field with 6, but it's not the correct way to check if the product has a route with ID 6.

You should use the in operator to check if the route with ID 6 is in the 'route_ids' list. Here's the corrected code:

for record in records:
  if 6 in record['route_ids']:
    if not record['default_code']:
      record['default_code'] = env['ir.sequence'].next_by_code('manufactured_product.default_code')
  else:
    raise UserError(_("Product is not manufactured."))


Hope it helps

1
Avatar
Descartar
Aleksander Steffensen
Autor

Thank you for the input! :-)
Unfortunately, it does not seem to work. Now, it will not generate the internal reference with any products. I'm not seeing any errors messages, but then I don't have any shell access so I wouldn't know. But it doesn't look like the conditions are met.

Avatar
Aleksander Steffensen
Autor Mejor respuesta

So using ChatGPT I was able to find a way that worked. I think there were some problems accessing the related field in stock.route from the server actions context. Here is the code that actually works:

for record in records:
    try:
        # Use sudo() to execute the operation with elevated privileges
        route_ids = record.sudo().route_ids.ids
       
        if 6 in route_ids:
            if not record.default_code:
                # Use Odoo API to update the record
                record.sudo().write({
                    'default_code': env['ir.sequence'].next_by_code('manufactured_product.default_code')
                })
    except Exception as e:
        # Handle the exception, print or log it as needed
        print(f"Error processing record: {e}")



I've got some concerns as to the security of this code. Any thoughts?


0
Avatar
Descartar
¿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
difference between server actions and client actions in Odoo? Resuelto
action server
Avatar
Avatar
Avatar
Avatar
3
jun 23
13362
How to create server action incoming in human resources?
action server email
Avatar
0
mar 15
4358
How to create server action incoming in human resources?
action server email
Avatar
Avatar
2
mar 15
7885
Send emails with automated action when a purchase request is created, odoo 13 community Resuelto
action mail server automation
Avatar
Avatar
1
mar 24
2825
Purpose of the Scheduled Action - "Base: Auto-vacuum internal data" ?
action server auto scheduled
Avatar
Avatar
Avatar
Avatar
4
oct 23
13827
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