Skip to Content
Odoo Menu
  • Prisijungti
  • Išbandykite nemokamai
  • Programėlės
    Finansai
    • Apskaita
    • Pateikimas apmokėjimui
    • Sąnaudos
    • Skaičiuoklė (BI)
    • Dokumentai
    • Pasirašymas
    Pardavimai
    • CRM
    • Pardavimai
    • Kasų sistema - Parduotuvė
    • Kasų sistema - Restoranas
    • Prenumeratos
    • Nuoma
    Svetainės
    • Svetainių kūrėjimo įrankis
    • El. Prekyba
    • Internetinis Tinklaraštis
    • Forumas
    • Tiesioginis pokalbis
    • eMokymasis
    Tiekimo grandinė
    • Atsarga
    • Gamyba
    • PLM
    • Įsigijimai
    • Priežiūra
    • Kokybė
    Žmogaus ištekliai
    • Darbuotojai
    • Įdarbinimas
    • Atostogos
    • Įvertinimai
    • Rekomendacijos
    • Transporto priemonės
    Rinkodara
    • Socialinė rinkodara
    • Rinkodara el. paštu
    • SMS rinkodara
    • Renginiai
    • Rinkodaros automatizavimas
    • Apklausos
    Paslaugos
    • Projektas
    • Darbo laiko žiniaraščiai
    • Priežiūros tarnyba
    • Pagalbos tarnyba
    • Planavimas
    • Rezervacijos
    Produktyvumas
    • Diskucija
    • Patvirtinimai
    • IoT
    • VoIP
    • Žinių biblioteka
    • WhatsApp
    Trečiųjų šalių programos Odoo Studija Odoo debesijos platforma
  • Pramonės šakos
    Mažmeninė prekyba
    • Knygynas
    • Drabužių parduotuvė
    • Baldų parduotuvė
    • Maisto prekių parduotuvė
    • Techninės įrangos parduotuvė
    • Žaislų parduotuvė
    Food & Hospitality
    • Barai ir pub'ai
    • Restoranas
    • Greitasis maistas
    • Guest House
    • Gėrimų platintojas
    • Hotel
    Real Estate
    • Real Estate Agency
    • Architektūros įmonė
    • Konstrukcija
    • Estate Managament
    • Sodininkauti
    • Turto savininkų asociacija
    Consulting
    • Accounting Firm
    • Odoo Partneris
    • Marketing Agency
    • Teisinė firma
    • Talentų paieška
    • Auditai & sertifikavimas
    Gamyba
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Įmonių dovanos
    Sveikata & Fitnesas
    • Sporto klubas
    • Akinių parduotuvė
    • Fitneso Centras
    • Sveikatos praktikai
    • Vaistinė
    • Kirpėjas
    Trades
    • Handyman
    • IT įranga ir palaikymas
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Aplinkos agentūra
    • Reklaminių stendų nuoma
    • Fotografavimas
    • Dviračių nuoma
    • Programinės įrangos perpardavėjas
    Browse all Industries
  • Bendrija
    Mokykitės
    • Mokomosios medžiagos
    • Dokumentacija
    • Sertifikatai
    • Mokymai
    • Internetinis Tinklaraštis
    • Tinklalaidės
    Skatinkite švietinimą
    • Švietimo programa
    • Scale Up! Verslo žaidimas
    • Aplankykite Odoo
    Gaukite programinę įrangą
    • Atsisiųsti
    • Palyginkite versijas
    • Leidimai
    Bendradarbiauti
    • Github
    • Forumas
    • Renginiai
    • Vertimai
    • Tapkite partneriu
    • Services for Partners
    • Registruokite jūsų apskaitos įmonę
    Gaukite paslaugas
    • Susiraskite partnerį
    • Susirask buhalterį
    • Susitikti su konsultantu
    • Diegimo paslaugos
    • Klientų rekomendavimas
    • Palaikymas
    • Atnaujinimai
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Gaukite demo
  • Kainodara
  • Pagalba

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

  • CRM
  • e-Commerce
  • Apskaita
  • Atsarga
  • PoS
  • Projektas
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Žymos (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Žymos (View all)
odoo accounting v14 pos v15
About this forum
Pagalba

prevent write on status field

Prenumeruoti

Get notified when there's activity on this post

This question has been flagged
contactsres.partnerwrite
4 Replies
1635 Rodiniai
Portretas
RacketRebel

I have defined a field in my script that is _inherint res.partners

lookup_status = fields.Integer(string = "Lookup status",
tracking = True,
readonly = True,
default = 0)

The field is  on the screen, it is internal by my script changed, when changed, the changed value is visible. The write function will not see the changed in the vals. 

def write(self, vals):

if 'ep_lookup_status' in vals:
count = vals['ep_lookup_status']
if count == 0:
raise ValidationError(_('EP Lookup status cannot be 0'))

super().write(vals)

Why is the changed value of lookup_status not in vals, it should be. What to to

0
Portretas
Atmesti
Christoph Farnleitner

Is lookup_status and ep_lookup_status meant to be the same? What and how is it even changed?

klause

Thanks for this :)

Portretas
Cybrosys Techno Solutions Pvt.Ltd
Best Answer

Hi,

Please refer to the code below:

from odoo import models, fields, api
from odoo.exceptions import ValidationError

class ResPartner(models.Model):
"""
Inherits the res.partner model to add a 'lookup_status' field.

This field is an internal indicator managed by backend processes.
It is set to readonly to prevent manual edits through the UI.

Constraints:
- The field 'lookup_status' must not be zero after any update.
Attempting to set it to 0 will raise a ValidationError.
"""

_inherit = 'res.partner'

lookup_status = fields.Integer(string="Lookup Status", tracking=True,
readonly=True, default=0)

@api.constrains('lookup_status')
def _check_lookup_status(self):
"""
Constraint to ensure that 'lookup_status' is never set to 0.

This method is automatically triggered whenever the 'lookup_status'
field is modified. It raises a ValidationError if the value is set to 0,
enforcing a business rule that prohibits this status value.

Raises:
ValidationError: If 'lookup_status' is equal to 0.
"""
for rec in self:
if rec.lookup_status == 0:
raise ValidationError(_('EP Lookup status cannot be 0'))

@api.constrains checks actual field values on the record after creation/update. It works regardless of whether the field was part of the original vals or changed indirectly.write() logic triggers for explicit values passed in the vals dictionary.


Hope it helps.

0
Portretas
Atmesti
RacketRebel
Autorius

Thanks for the answer, but it will not work, it took some time toe generate a slimline version to demonstrate the problem:

import logging

from odoo import api, fields, models
from odoo.addons.bag_ep_api.utils.buffer_manager import BufferManager
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)

# Odoo version 18

class ResPartner(models.Model):
_inherit = 'res.partner'

ep_lookup_status = fields.Integer(
string = "EP Lookup status",
tracking = True,
readonly = True,
default = 0
)

@api.model_create_multi
def create(self, vals_list):
partners = super().create(vals_list)

return partners

def write(self, vals):

# if buffer is not active, this will do nothing, also no message the api.constrains will also not work
# when activate in the _onchange it wil preform exact as expected, workaround
buffer = BufferManager.get(self.env.user.id)
if buffer:
for key in buffer:
if key not in vals:
vals[key] = buffer[key]

result = super().write(vals)
for record in self:

if record.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')

return result

@api.constrains('ep_lookup_status')
def _check_ep_lookup_status(self):
for rec in self:
if rec.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')

@api.onchange('zip')
def _onchange_zip(self):

# some other code with channing the ep_lookup_status
# for demo

if self.zip == '2035 VS':
self.ep_lookup_status = 1;
else:
self.ep_lookup_status = 0;

BufferManager.set(self.env.user.id,'ep_lookup_status', self.ep_lookup_status)

return self._handle_onchange_result(
ep_lookup_status = self.ep_lookup_status,
)

@staticmethod
def _handle_onchange_result(warnings = None, model_name = None, data_model = None, ep_lookup_status = None):
# #
result = {}
warnings = {}

# some other to infor the user(s)

# Show a warning message if needed
if warnings:
result['warning'] = {
'title': " -- Warning -- ",
'message': "\n".join(warnings),
}

return result or None

RacketRebel
Autorius

the indents are gone, sorry

RacketRebel
Autorius

with the appropriate tabs, indents: </>
import logging

from odoo import api, fields, models
from odoo.addons.bag_ep_api.utils.buffer_manager import BufferManager
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)

# Odoo version 18

class ResPartner(models.Model):
_inherit = 'res.partner'

ep_lookup_status = fields.Integer(
string = "EP Lookup status",
tracking = True,
readonly = True,
default = 0
)

@api.model_create_multi
def create(self, vals_list):
partners = super().create(vals_list)

return partners

def write(self, vals):

# if buffer is not active, this will do nothing, also no message the api.constrains will also not work
# when activate in the _onchange it wil preform exact as expected, workaround
buffer = BufferManager.get(self.env.user.id)
if buffer:
for key in buffer:
if key not in vals:
vals[key] = buffer[key]

result = super().write(vals)
for record in self:

if record.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')

return result

@api.constrains('ep_lookup_status')
def _check_ep_lookup_status(self):
for rec in self:
if rec.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')

@api.onchange('zip')
def _onchange_zip(self):

# some other code with channing the ep_lookup_status
# for demo

if self.zip == '2035 VS':
self.ep_lookup_status = 1;
else:
self.ep_lookup_status = 0;

BufferManager.set(self.env.user.id,'ep_lookup_status', self.ep_lookup_status)

return self._handle_onchange_result(
ep_lookup_status = self.ep_lookup_status,
)

@staticmethod
def _handle_onchange_result(warnings = None, model_name = None, data_model = None, ep_lookup_status = None):
# #
result = {}
warnings = {}

# some other to infor the user(s)

# Show a warning message if needed
if warnings:
result['warning'] = {
'title': " -- Warning -- ",
'message': "\n".join(warnings),
}

return result or None

Portretas
RacketRebel
Autorius Best Answer

Yes these are the same, the status is changed in a .py when i fetch some data. The status is displayed correct, according to the current value, but not in the vals. There are only in vals when the user touch the field. So all writes will not recognise when the change by a program. The fields needs deforced to update. Think need to write a work around, with a cache / buffer to updater the vals.


her is a slimline example of the problem, also with the workaround to get it working with an bi=uffer to store the value.

import logging


from odoo import api, fields, models
from odoo.addons.bag_ep_api.utils.buffer_manager import BufferManager
from odoo.exceptions import ValidationError


_logger = logging.getLogger(__name__)


# Odoo version 18

class ResPartner(models.Model):
_inherit = 'res.partner'

ep_lookup_status = fields.Integer(
string = "EP Lookup status",
tracking = True,
readonly = True,
default = 0
)


@api.model_create_multi
def create(self, vals_list):
partners = super().create(vals_list)

return partners


def write(self, vals):

# if buffer is not active, this will do nothing, also no message the api.constrains will also not work
# when activate in the _onchange it wil preform exact as expected, workaround
buffer = BufferManager.get(self.env.user.id)
if buffer:
for key in buffer:
if key not in vals:
vals[key] = buffer[key]

result = super().write(vals)
for record in self:

if record.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')

return result


@api.constrains('ep_lookup_status')
def _check_ep_lookup_status(self):
for rec in self:
if rec.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')


@api.onchange('zip')
def _onchange_zip(self):

# some other code with channing the ep_lookup_status
# for demo

if self.zip == '2035 VS':
self.ep_lookup_status = 1;
else:
self.ep_lookup_status = 0;

BufferManager.set(self.env.user.id,'ep_lookup_status', self.ep_lookup_status)

return self._handle_onchange_result(
ep_lookup_status = self.ep_lookup_status,
)


@staticmethod
def _handle_onchange_result(warnings = None, model_name = None, data_model = None, ep_lookup_status = None):
# #
result = {}
warnings = {}

# some other to infor the user(s)

# Show a warning message if needed
if warnings:
result['warning'] = {
'title': " -- Warning -- ",
'message': "\n".join(warnings),
}

return result or None
0
Portretas
Atmesti
Christoph Farnleitner

Provide an installable but reduced-to-the-problem example of what you've got right now, including manifest, views, and that ominous 'internal script' that changes stuff, things can be worked out. Currently it's just guess work of what your setup looks like and whether you've even used the correct attribute names (i.e. 'ep_lookup_status' vs 'lookup_status').

Portretas
Manish Bohra
Best Answer

Hello RacketRebel,

Try below code : 

def write(self, vals):

    res = super().write(vals)

    for rec in self:

        if rec.lookup_status == 0:

            raise ValidationError(_('EP Lookup status cannot be 0'))

        else:

            rec.update({'lookup_status':rec.lookup_status})

    return res


thanks.

0
Portretas
Atmesti
Portretas
D Enterprise
Best Answer

Hii,

Why Your Check Fails

Your logic:

It only works if lookup_status is in vals, but:

  • If the field was updated via code, and
  • You're calling record.write({}) or record.write({'other_field': val})

Then lookup_status won’t be in vals, so your check silently skips.


Here is updated code 
Check current field value directly on self

If you want to ensure the value isn’t 0 when any write() happens:

def write(self, vals):

    res = super().write(vals)

   

    for rec in self:

        if rec.lookup_status == 0:

            raise ValidationError(_('EP Lookup status cannot be 0'))

   

    return res

try this 

i hope it is use full

0
Portretas
Atmesti
RacketRebel
Autorius

The suggested solution did not seem to work. The status displayed on the screen remains 0, while the stored old value is 3. Since the new value is not present in vals, the update does not occur, and as a result, the raise ValidationError is not triggered.

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

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

Registracija
Related Posts Replies Rodiniai Veikla
Need help with [v15] ValueError: Invalid field 'total_due' on model 'res.partner' Solved
contacts res.partner
Portretas
Portretas
1
birž. 23
5133
Partner_id name, name
contacts res.partner
Portretas
Portretas
1
birž. 22
7881
Make 'opt-out' checkbox settable per each contact of a company (partner)
contacts res.partner
Portretas
0
kov. 15
4897
Clickable "Contacts & Addresses" inside res.partner Solved
contacts res.partner partners
Portretas
Portretas
Portretas
Portretas
Portretas
8
vas. 24
15899
Odoo 13 CE record rule: Restricting salesman from seeing other contacts base on the defined salesperson in contact form
contacts res.partner record_rule
Portretas
Portretas
3
rugp. 20
4527
Bendrija
  • Mokomosios medžiagos
  • Dokumentacija
  • Forumas
Atvirasis kodas
  • Atsisiųsti
  • Github
  • Runbot
  • Vertimai
Paslaugos
  • Odoo.sh talpinimas
  • Palaikymas
  • Atnaujinti
  • Pritaikytas programavimo kūrimas
  • Švietimas
  • Susirask buhalterį
  • Susiraskite partnerį
  • Tapkite partneriu
Apie mus
  • Mūsų įmonė
  • Prekės ženklo turtas
  • Susisiekite su mumis
  • Darbo pasiūlymai
  • Renginiai
  • Tinklalaidės
  • Internetinis Tinklaraštis
  • Klientai
  • Teisinis • Privatumas
  • Saugumas
الْعَرَبيّة 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 yra atvirojo kodo verslo programų rinkinys, kuris apima visas įmonės poreikius: CRM, El. Prekybą, Apskaitą, Atsargų, Kasų sistemą, Projektų valdymą ir kt.

Unikali Odoo vertės pasiūla – būti tuo pačiu metu labai lengvai naudojama ir visiškai integruota sistema.

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