Passa al contenuto
Odoo Menu
  • Accedi
  • Provalo gratis
  • App
    Finanze
    • Contabilità
    • Fatturazione
    • Note spese
    • Fogli di calcolo (BI)
    • Documenti
    • Firma
    Vendite
    • CRM
    • Vendite
    • Punto vendita Negozio
    • Punto vendita Ristorante
    • Abbonamenti
    • Noleggi
    Siti web
    • Configuratore sito web
    • E-commerce
    • Blog
    • Forum
    • Live chat
    • E-learning
    Supply chain
    • Magazzino
    • Produzione
    • PLM
    • Acquisti
    • Manutenzione
    • Qualità
    Risorse umane
    • Dipendenti
    • Assunzioni
    • Ferie
    • Valutazioni
    • Referral dipendenti
    • Parco veicoli
    Marketing
    • Social marketing
    • E-mail marketing
    • SMS marketing
    • Eventi
    • Marketing automation
    • Sondaggi
    Servizi
    • Progetti
    • Fogli ore
    • Assistenza sul campo
    • Helpdesk
    • Pianificazione
    • Appuntamenti
    Produttività
    • Comunicazioni
    • Approvazioni
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    App di terze parti Odoo Studio Piattaforma cloud Odoo
  • Settori
    Retail
    • Libreria
    • Negozio di abbigliamento
    • Negozio di arredamento
    • Alimentari
    • Ferramenta
    • Negozio di giocattoli
    Cibo e ospitalità
    • Bar e pub
    • Ristorante
    • Fast food
    • Pensione
    • Grossista di bevande
    • Hotel
    Agenzia immobiliare
    • Agenzia immobiliare
    • Studio di architettura
    • Edilizia
    • Gestione immobiliare
    • Impresa di giardinaggio
    • Associazione di proprietari immobiliari
    Consulenza
    • Società di contabilità
    • Partner Odoo
    • Agenzia di marketing
    • Studio legale
    • Selezione del personale
    • Audit e certificazione
    Produzione
    • Tessile
    • Metallo
    • Arredamenti
    • Alimentare
    • Birrificio
    • Ditta di regalistica aziendale
    Benessere e sport
    • Club sportivo
    • Negozio di ottica
    • Centro fitness
    • Centro benessere
    • Farmacia
    • Parrucchiere
    Commercio
    • Tuttofare
    • Hardware e assistenza IT
    • Ditta di installazione di pannelli solari
    • Calzolaio
    • Servizi di pulizia
    • Servizi di climatizzazione
    Altro
    • Organizzazione non profit
    • Ente per la tutela ambientale
    • Agenzia di cartellonistica pubblicitaria
    • Studio fotografico
    • Punto noleggio di biciclette
    • Rivenditore di software
    Carica tutti i settori
  • Community
    Apprendimento
    • Tutorial
    • Documentazione
    • Certificazioni 
    • Formazione
    • Blog
    • Podcast
    Potenzia la tua formazione
    • Programma educativo
    • Scale Up! Business Game
    • Visita Odoo
    Ottieni il software
    • Scarica
    • Versioni a confronto
    • Note di versione
    Collabora
    • Github
    • Forum
    • Eventi
    • Traduzioni
    • Diventa nostro partner
    • Servizi per partner
    • Registra la tua società di contabilità
    Ottieni servizi
    • Trova un partner
    • Trova un contabile
    • Incontra un esperto
    • Servizi di implementazione
    • Testimonianze dei clienti
    • Supporto
    • Aggiornamenti
    GitHub Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Richiedi una demo
  • Prezzi
  • Aiuto

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

  • CRM
  • e-Commerce
  • Contabilità
  • Magazzino
  • PoS
  • Progetti
  • MRP
All apps
È necessario essere registrati per interagire con la community.
Tutti gli articoli Persone Badge
Etichette (Mostra tutto)
odoo accounting v14 pos v15
Sul forum
È necessario essere registrati per interagire con la community.
Tutti gli articoli Persone Badge
Etichette (Mostra tutto)
odoo accounting v14 pos v15
Sul forum
Assistenza

Is it possible to enforce a float field in a form to accept values only between 0 and 99?

Iscriviti

Ricevi una notifica quando c'è un'attività per questo post

La domanda è stata contrassegnata
viewsfieldsxmlformmargin
5 Risposte
8510 Visualizzazioni
Avatar
E.M.

I am looking the user to enter a % (sales margin) between 0 and 99.

Is it possible to enforce that the float field will accept only values between x and y?

If so, how?,

and,

would it be possible to popup a message informing the user that he has to enter something between that x and y values?


Note: I am not looking to know how to add the field, just how to enforce that a defined field accept values only between x and y.

0
Avatar
Abbandona
Avatar
E.M.
Autore Risposta migliore

I added the constraint as stated in the 'Model constraints' section of documentation but it does not seem to trigger anything, does it have to be included within the class definition? Is there something missing?

# -*- coding: utf-8 -*-
from openerp import models, fields, api
from openerp.exceptions import ValidationError

class sale_order_line(models.Model):

_inherit = "sale.order.line"

sale_margin_percent = fields.Float('Margen de Ventas (%)', (4, 2))

def update_sale_margin(self, cr, uid, ids, price_unit, purchase_price, discount):
print 'update_sale_margin'
....
return {'value': {'sale_margin_percent': sale_margin } }

def update_sale_price(self, cr, uid, ids, sale_margin_percent, purchase_price, discount):
print 'update_sale_price'
....
        return {'value': {'price_unit': sale_price } }

@api.one
@api.constrains('sale_margin_percent')
def _check_margin(self):
print '_check_margin'
if self.sale_margin_percent >= 100:
raise ValidationError("El margen de venta no puede ser superior al 100%")
# all records passed the test, don't return anything


[****UPDATE*****]

Following zbik comment, I have rewritten the code as follows:


# -*- coding: utf-8 -*-
from openerp import models, fields, api, exceptions

class sale_order_line(models.Model):

_inherit = "sale.order.line"

sale_margin_percent = fields.Float('Margen de Ventas (%)', (4, 2))

@api.onchange('price_unit')
def update_sale_margin(self, price_unit, purchase_price, discount):
print 'update_sale_margin'
...
        return {'value': {'sale_margin_percent': sale_margin } }

    @api.onchange('sale_margin_percent', 'purchase_price')
    def update_sale_price(self, sale_margin_percent, purchase_price, discount):
       print 'update_sale_price'
...
        return {'value': {'price_unit': sale_price } }

    @api.constrains('sale_margin_percent')
    def _check_margin(self):
        print '_check_margin'
        if self.sale_margin_percent >= 100:
            raise exceptions.ValidationError("El margen de venta no puede ser superior al 100%")
         # all records passed the test, don't return anything


The attribute added is:

<xpath expr="//field[@name='order_line']/tree//field[@name='price_unit']" position="attributes">
<attribute name="on_change">update_sale_margin(price_unit, purchase_price, discount)</attribute>
</xpath>


But I get the following error:

Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 537, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 574, in dispatch
    result = self._call_function(**self.params)
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 310, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 113, in wrapper
    return f(dbname, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 307, in checked_call
    return self.endpoint(*a, **kw)
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 803, in __call__
    return self.method(*args, **kw)
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 403, in response_wrap
    response = f(*args, **kw)
  File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 944, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 936, in _call_kw
    return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 241, in wrapper
    return old_api(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 363, in old_api
    result = method(recs, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 5864, in onchange
    record._onchange_eval(name, field_onchange[name], result)
  File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 5782, in _onchange_eval
    method_res = getattr(self._model, method)(*args)
TypeError: update_sale_margin() takes exactly 4 arguments (7 given) 


Hope someone can help.


0
Avatar
Abbandona
Zbik

You mix old and new api. on_change in new api works with decorator @api.onchange. Probably in this trouble.

E.M.
Autore

Thanks zbik, I have tried to unify to new api, but I can't make the on_change update functions work with the new api. You can see code above.

Avatar
Zbik
Risposta migliore

See Model constraints in documentation. Example from doc:

from openerp.exceptions import ValidationError

@api.constrains('age')
def _check_something(self):
    for record in self:
        if record.age > 20:
            raise ValidationError("Your record is too old: %s" % record.age)
    # all records passed the test, don't return anything 


0
Avatar
Abbandona
E.M.
Autore

I added the constraint as stated in the 'Model constraints' section of documentation but it does not seem to trigger anything, does it have to be included within the class definition? Is there something missing? # -*- coding: utf-8 -*- from openerp import models, fields, api class sale_order_line(models.Model): _inherit = "sale.order.line" sale_margin_percent = fields.Float('Margen de Ventas (%)', (4, 2)) def update_sale_margin(self, cr, uid, ids, price_unit, purchase_price, discount): print 'update_sale_margin' .... return {'value': {'sale_margin_percent': sale_margin } } def update_sale_price(self, cr, uid, ids, sale_margin_percent, purchase_price, discount): print 'update_sale_price' ... return {'value': {'price_unit': sale_price } } @api.one @api.constrains('sale_margin_percent') def _check_margin(self): print '_check_margin' if self.sale_margin_percent >= 100: raise ValidationError("El margen de venta no puede ser superior al 100%") # all records passed the test, don't return anything

E.M.
Autore

Sorry, see attached answer with proper formatting (-not enough karma to convert as an answer or delete de comment-).

Avatar
Tarek Mohamed Ibrahim
Risposta migliore

I think you have to write an 'on_change' method and attache it in the xml to the field you need to enforce its value

field in xml will be like the following:

...
<field name="percent_field" on_change="onchange_percent_field(percent_field)"/>
...

you have to create a method onchange_percent_field and put in it your check, if the value is out of your range then you have to set the value of the field to its old value and  raise an exception 


0
Avatar
Abbandona
E.M.
Autore

I would prefer to let the on_change function for actual on_change activities. I see that more as a trigger than a constraint.

Ti stai godendo la conversazione? Non leggere soltanto, partecipa anche tu!

Crea un account oggi per scoprire funzionalità esclusive ed entrare a far parte della nostra fantastica community!

Registrati
Post correlati Risposte Visualizzazioni Attività
Hello, I would like to know where I can edit the xml of this part of the form view
views xml form
Avatar
Avatar
1
nov 22
4193
How to align checkboxes, in a single line in form? Risolto
views fields form V17
Avatar
Avatar
Avatar
2
lug 24
2728
Inherited form view for specific module without overriding base view - Odoo 15.0
views modules xml form
Avatar
Avatar
1
mar 22
4077
Odoo 13: Form view inherit Risolto
views xml form html
Avatar
Avatar
Avatar
Avatar
4
giu 21
7786
How to have multiple views inside a xml file? Risolto
views fields xml resources
Avatar
Avatar
1
gen 21
5054
Community
  • Tutorial
  • Documentazione
  • Forum
Open source
  • Scarica
  • Github
  • Runbot
  • Traduzioni
Servizi
  • Hosting Odoo.sh
  • Supporto
  • Aggiornamenti
  • Sviluppi personalizzati
  • Formazione
  • Trova un contabile
  • Trova un partner
  • Diventa nostro partner
Chi siamo
  • La nostra azienda
  • Branding
  • Contattaci
  • Lavora con noi
  • Eventi
  • Podcast
  • Blog
  • Clienti
  • Note legali • Privacy
  • Sicurezza
الْعَرَبيّة 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 è un gestionale di applicazioni aziendali open source pensato per coprire tutte le esigenze della tua azienda: CRM, Vendite, E-commerce, Magazzino, Produzione, Fatturazione elettronica, Project Management e molto altro.

Il punto di forza di Odoo è quello di offrire un ecosistema unico di app facili da usare, intuitive e completamente integrate tra loro.

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