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

The value of the onchange function shows up in the form but does not save in the database.

Subscriure's

Get notified when there's activity on this post

This question has been flagged
on_changeodoo8.0
4 Respostes
14244 Vistes
Avatar
Anand Prasanth

I have an age calculation function (onchange) and it calculates and shows up in the form when I enter the data. But the data is not saved in the data base. Please help with the code.


    @api.onchange('dob')

     def onchange_age_calculate(self):

      if not self.dob:

       self.age = 0

     else:

      today_date = datetime.datetime.now().year

      date_split = self.dob.split('-',1)

      birth_year = date_split[0]

      self.age = today_date -int(birth_year)


    _columns = {

                'name': fields.char(string="Name"), 

                'dob' : fields.date('Date of Birth'),

                'age' : fields.float( string='Age')


I have imported date time and the required library files hope so

1
Avatar
Descartar
Sehrish

Reference: https://learnopenerp.blogspot.com/2021/10/onchange-method-readonly-field-not-store-database-odoo.html

Avatar
Axel Mendoza
Best Answer

That could be happening if you declare readonly the field age in the view. The readonly fields are not saved into the database even when they change their value through an onchange. To solve just remove the readonly attr or recalculate it in the create/write method of your model or define it as an computed field. There are solutions to send the readonly fields to the create/write methods but it's not out of the box

3
Avatar
Descartar
Avatar
ayman mohammed adam
Best Answer

hello try this


   @api.onchange('dob')

   @api.depends('dob')

     def onchange_age_calculate(self):

      if not self.dob:

       self.age = 0

     else:

      today_date = datetime.datetime.now().year

      date_split = self.dob.split('-',1)

      birth_year = date_split[0]

      self.age = today_date -int(birth_year)

 

      name=  fields.Char(string="Name"), 

      dob' = fields.Date('Date of Birth'),

      age= fields.Float( string='Age')



then replace your class like this

class your_class_name(models.Model):


Thanks and I hoped i help you.

0
Avatar
Descartar
Avatar
Pawan
Best Answer

Anand,

As axel said you cant store readonly values in DB, i got some workout around it to do that..

To store readonly values also in future, u can have a little modification at your js part:

at wed/static/src/js/views/view_form.js        under FormView class, at method '_process_save()'

approx at line# 873, under "else if (f.name !== 'id' && (!self.datarecord.id || f._dirty_flag))"

replace the code with below one....

else if (f.name !== 'id' && (!self.datarecord.id || f._dirty_flag)){

//commenting below lines to allow sotring readonly values also

// if (!f.get("readonly")) {

               // values[f.name] = f.get_value(true);

    // } else {

            // readonly_values[f.name] = f.get_value(true);

    // }

    values[f.name] = f.get_value();

     if (f.get("readonly"))

            readonly_values[f.name]= f.get_value();

}

Hope this will help you

0
Avatar
Descartar
Avatar
Kirubanidhi Rajarathinam
Best Answer

# Specify below header file in your code:

from datetime import datetime

from dateutil import relativedelta as rdelta

from datetime import date

#create a two field in your py file

staff_dob = fields.Date(string="Date of Birth")

staff_age = fields.Integer(string="Age")

# We can use onchange method in my staff_dob field .

@api.onchange('staff_dob')

def age_cal_fun(self):

if self.staff_dob:

today = date.today()

bdate = datetime.strptime(self.staff_dob, '%Y-%m-%d')

rd = rdelta.relativedelta(today, bdate)

self.staff_age = rd.years

#Above this code is help for you

0
Avatar
Descartar
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
On_change: help! Solved
on_change uppercase odoo8.0
Avatar
Avatar
Avatar
2
d’ag. 15
4548
how to implement joint piece in odoo 8 in one view
odoo8.0
Avatar
0
d’abr. 24
2640
what is the reason behind extra move? in stock
odoo8.0
Avatar
Avatar
Avatar
Avatar
4
de nov. 23
6814
How to solve fields.function issue in odoo 8
odoo8.0
Avatar
0
d’oct. 23
2646
how to restrict create and delete access in one2many field tree view
odoo8.0
Avatar
0
de des. 22
3362
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