Skip to Content
Odoo Menu
  • Prijavi
  • Try it free
  • Apps
    Finance
    • Accounting
    • Invoicing
    • Expenses
    • Spreadsheet (BI)
    • Documents
    • Sign
    Sales
    • CRM
    • Sales
    • POS Shop
    • POS Restaurant
    • Subscriptions
    • Rental
    Websites
    • Website Builder
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Supply Chain
    • Inventory
    • Manufacturing
    • PLM
    • Purchase
    • Maintenance
    • Quality
    Human Resources
    • Employees
    • Recruitment
    • Time Off
    • Appraisals
    • Referrals
    • Fleet
    Marketing
    • Social Marketing
    • Email Marketing
    • SMS Marketing
    • Events
    • Marketing Automation
    • Surveys
    Services
    • Project
    • Timesheets
    • Field Service
    • Helpdesk
    • Planning
    • Appointments
    Productivity
    • Discuss
    • Approvals
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    Third party apps Odoo Studio Odoo Cloud Platform
  • Industries
    Retail
    • Book Store
    • Clothing Store
    • Furniture Store
    • Grocery Store
    • Hardware Store
    • Toy Store
    Food & Hospitality
    • Bar and Pub
    • Restaurant
    • Fast Food
    • Guest House
    • Beverage Distributor
    • Hotel
    Real Estate
    • Real Estate Agency
    • Architecture Firm
    • Construction
    • Estate Management
    • Gardening
    • Property Owner Association
    Consulting
    • Accounting Firm
    • Odoo Partner
    • Marketing Agency
    • Law firm
    • Talent Acquisition
    • Audit & Certification
    Manufacturing
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Corporate Gifts
    Health & Fitness
    • Sports Club
    • Eyewear Store
    • Fitness Center
    • Wellness Practitioners
    • Pharmacy
    • Hair Salon
    Trades
    • Handyman
    • IT Hardware & Support
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Environmental Agency
    • Billboard Rental
    • Photography
    • Bike Leasing
    • Software Reseller
    Browse all Industries
  • Community
    Learn
    • Tutorials
    • Documentation
    • Certifications
    • Training
    • Blog
    • Podcast
    Empower Education
    • Education Program
    • Scale Up! Business Game
    • Visit Odoo
    Get the Software
    • Download
    • Compare Editions
    • Releases
    Collaborate
    • Github
    • Forum
    • Events
    • Translations
    • Become a Partner
    • Services for Partners
    • Register your Accounting Firm
    Get Services
    • Find a Partner
    • Find an Accountant
    • Meet an advisor
    • Implementation Services
    • Customer References
    • Support
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Get a demo
  • Pricing
  • Help

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

  • CRM
  • e-Commerce
  • Knjigovodstvo
  • Zaloga
  • PoS
  • Projekt
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Ključne besede (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Ključne besede (View all)
odoo accounting v14 pos v15
About this forum
Pomoč

prevent write on status field

Naroči se

Get notified when there's activity on this post

This question has been flagged
contactsres.partnerwrite
4 Odgovori
1612 Prikazi
Avatar
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
Avatar
Opusti
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 :)

Avatar
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
Avatar
Opusti
RacketRebel
Avtor

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
Avtor

the indents are gone, sorry

RacketRebel
Avtor

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

Avatar
RacketRebel
Avtor 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
Avatar
Opusti
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').

Avatar
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
Avatar
Opusti
Avatar
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
Avatar
Opusti
RacketRebel
Avtor

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!

Prijavi
Related Posts Odgovori Prikazi Aktivnost
Need help with [v15] ValueError: Invalid field 'total_due' on model 'res.partner' Solved
contacts res.partner
Avatar
Avatar
1
jun. 23
5112
Partner_id name, name
contacts res.partner
Avatar
Avatar
1
jun. 22
7861
Make 'opt-out' checkbox settable per each contact of a company (partner)
contacts res.partner
Avatar
0
mar. 15
4892
Clickable "Contacts & Addresses" inside res.partner Solved
contacts res.partner partners
Avatar
Avatar
Avatar
Avatar
Avatar
8
feb. 24
15875
Odoo 13 CE record rule: Restricting salesman from seeing other contacts base on the defined salesperson in contact form
contacts res.partner record_rule
Avatar
Avatar
3
avg. 20
4522
Community
  • Tutorials
  • Documentation
  • Forum
Open Source
  • Download
  • Github
  • Runbot
  • Translations
Services
  • Odoo.sh Hosting
  • Support
  • Upgrade
  • Custom Developments
  • Education
  • Find an Accountant
  • Find a Partner
  • Become a Partner
About us
  • Our company
  • Brand Assets
  • Contact us
  • Jobs
  • Events
  • Podcast
  • Blog
  • Customers
  • Legal • Privacy
  • Security
الْعَرَبيّة 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 is a suite of open source business apps that cover all your company needs: CRM, eCommerce, accounting, inventory, point of sale, project management, etc.

Odoo's unique value proposition is to be at the same time very easy to use and fully integrated.

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