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

Raise exception in an custom method

Suscribirse

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

Se marcó esta pregunta
warningexception
1 Responder
11141 Vistas
Avatar
Soohoo
    _logger = logging.getLogger(__name__)

list_type = [
    ('full', 'Full Container'),
    ('loose', 'Loose Freight')
]

list_mode = [
    ('D2D', 'CY/CY - (Door to Door)'),
    ('D2P', 'CY/CY - (Door to Port)'),
    ('P2D', 'CY/CY - (Port to Door)'),
    ('P2P-1', 'CY/CY - (Port to Port)'),
    ('P2P-2', 'CFS/CY - (Port to Port)'),
    ('P2P-3', 'CFS/CFS - (Port to Port)'),
    ('other', 'Others')
]

list_container_size = [
    ('20"C', '20 Inch Container'),
    ('40"C', '40 Inch Container'),
    ('40"HQ', '40 Inch HQ Container'),
    ('40"R', '40 Inch Refer Container'),
    ('45"C', '45 Inch Container'),
    ('45"HQ', '45 Inch HQ Container')
]

list_transit_time = []
for i in range(1,365):
    if i == 1 :
        list_transit_time.append((i,str(i) + ' Day'))
    else:
        list_transit_time.append((i,str(i) + ' Days'))


#here generating the charges key which will be act as a unique key
def _generate_unique_key(self, cr, uid, ids, field_name, arg, context=None):
    result = {}
    for record in self.browse(cr, uid, ids, context=context):
        result[record.id] = str(record.port_lading_id.id) + '-' + str(record.port_unlading_id.id) + '-' + \
                            str(record.type) + '-' + str(record.mode) + '-' + str(record.via)
    return result


class shipment_charge(osv.osv):
    _name = 'shipment.charge'
    _columns = {
        'port_lading_id': fields.many2one('shipment.port', 'Port Lading', required=True, domain=[('port_lading', '=', 1)], store=True),
        'port_unlading_id': fields.many2one('shipment.port', 'Port Unlading', required=True, domain=[('port_unlading', '=' , 1)], store=True),
        'shipment_charge_price_ids': fields.one2many ('shipment.charge.price', 'shipment_charge_id', 'Container Quote'),
        'type': fields.selection(list_type, 'Type', required=True, help="Select Full Or loose Freight"),
        'mode': fields.selection(list_mode, 'Mode', required=True, help="Mode Of Container shipment"),
        'transit_time': fields.selection(list_transit_time, 'Transit Time', required=True, help="Transit Time In days"),
        'via':  fields.char('Via', size=64, help="Route , Via"),
        #two fields are missing have to update, agent_id and supplier_id
        'expiry_date': fields.date('Expiry Date',size=30, required=True, help='expiry date of this rates/charges after this date '
                                                               'charges ma be differ.'),
        'notes': fields.text('Notes', help='Notes Extra Information'),
        'charges_key':  fields.function(_generate_unique_key,type='char', method=True, store=True,
                                        string='charges_key', help="Charges key is a unique key for charges with "
                                                                   "combination of POL, POD, Agent, Supplier, Via, "
                                                                   "Mode separated with hyphens"),
    }

    _sql_constraints = [
        ('charges_key_unique', 'unique (charges_key)','The Charges key is not Unique'),
    ]

    #here generating the charges key which will be act as a unique key
    def onchange_generate_unique_key(self, cr, uid, ids, port_lading_id, port_unlading_id):
        _logger.warning("IMPORT-LOG : in onchange function")
        charges_key = str(port_lading_id) + '-' + str (port_unlading_id)
        return {'value': {'charges_key': charges_key}}

Above is my module code , and i have a written custom function _generate_unique_key() which generates the unique charges as per

_sql_constraints = [
    ('charges_key_unique', 'unique (charges_key)','The Charges key is not Unique'),
]

but function freezes when it give _sql_constraints errors

error in log is IntegrityError: duplicate key value violates unique constraint "shipment_charge_charges_key_unique" DETAIL: Key (charges_key)=(1-3-full-D2D-Dir) already exists.

please suggest how to raise error when it counters the duplicate value

Thanks in advance

3
Avatar
Descartar
Avatar
ASP
Mejor respuesta

Hi there,

If you want to show an alert or popup for Error/Warning, then you may try the following :

-> from openerp.tools.translate import _ (at the beginning of the file)

-> then you for validating unique constraint you can define your custom method and pass the value to it.

-> for alert/popup when error occurs, you can use :

raise osv.except_osv(_("Warning"), _("My warning Msg"))

or, if you want an error popup try this : raise osv.except_osv(_("Error!"), _("My error Msg"))

Please check this one and update me if this is useful for you or not, and if you want I can share a code snippet of mine where I've referred to a custom validation method for doing operation upon specific condition. (if.....else)

Cheers

:)

1
Avatar
Descartar
Soohoo
Autor

Thanks but how can i use this with

'charges_key': fields.function(_generate_unique_key,type='char', method=True, store=True,

¿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
Throwing "UncaughtPromiseError > KeyNotFoundError" error when attempting to edit the Action of the form field
exception
Avatar
0
dic 23
2783
How to Save Record After Showing Warning Message in Odoo 12
warning
Avatar
Avatar
Avatar
2
dic 19
10119
model cache has been invalidated
warning
Avatar
0
nov 19
5216
Error on Warning in Odoo 12 Resuelto
warning
Avatar
Avatar
1
jul 19
7841
how to show information on web side which is supplied by running py function?
warning
Avatar
0
jul 19
3305
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