Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

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

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

Raise exception in an custom method

Subscriure's

Get notified when there's activity on this post

This question has been flagged
warningexception
1 Respondre
11135 Vistes
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
Best Answer

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,

Enjoying the discussion? Don't just read, join in!

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

Registrar-se
Related Posts Respostes Vistes Activitat
Throwing "UncaughtPromiseError > KeyNotFoundError" error when attempting to edit the Action of the form field
exception
Avatar
0
de des. 23
2782
How to Save Record After Showing Warning Message in Odoo 12
warning
Avatar
Avatar
Avatar
2
de des. 19
10117
model cache has been invalidated
warning
Avatar
0
de nov. 19
5212
Error on Warning in Odoo 12 Solved
warning
Avatar
Avatar
1
de jul. 19
7837
how to show information on web side which is supplied by running py function?
warning
Avatar
0
de jul. 19
3301
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة 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 és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

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