Se rendre au contenu
Odoo Menu
  • Se connecter
  • Essai gratuit
  • Applications
    Finance
    • Comptabilité
    • Facturation
    • Notes de frais
    • Feuilles de calcul (BI)
    • Documents
    • Signature
    Ventes
    • CRM
    • Ventes
    • PdV Boutique
    • PdV Restaurant
    • Abonnements
    • Location
    Sites web
    • Site Web
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Chaîne d'approvisionnement
    • Inventaire
    • Fabrication
    • PLM
    • Achats
    • Maintenance
    • Qualité
    Ressources Humaines
    • Employés
    • Recrutement
    • Congés
    • Évaluations
    • Recommandations
    • Parc automobile
    Marketing
    • Marketing Social
    • E-mail Marketing
    • SMS Marketing
    • Événements
    • Marketing Automation
    • Sondages
    Services
    • Projet
    • Feuilles de temps
    • Services sur Site
    • Assistance
    • Planification
    • Rendez-vous
    Productivité
    • Discussion
    • Validations
    • Internet des Objets
    • VoIP
    • Connaissances
    • WhatsApp
    Applications tierces Odoo Studio Plateforme Cloud d'Odoo
  • Industries
    Commerce de détail
    • Librairie
    • Magasin de vêtements
    • Magasin de meubles
    • Épicerie
    • Quincaillerie
    • Magasin de jouets
    Food & Hospitality
    • Bar et Pub
    • Restaurant
    • Fast-food
    • Maison d’hôtes
    • Distributeur de boissons
    • Hôtel
    Immobilier
    • Agence immobilière
    • Cabinet d'architecture
    • Construction
    • Gestion immobilière
    • Jardinage
    • Association de copropriétaires
    Consultance
    • Cabinet d'expertise comptable
    • Partenaire Odoo
    • Agence Marketing
    • Cabinet d'avocats
    • Aquisition de talents
    • Audit & Certification
    Fabrication
    • Textile
    • Métal
    • Meubles
    • Alimentation
    • Brewery
    • Cadeaux d'entreprise
    Santé & Fitness
    • Club de sports
    • Opticien
    • Salle de fitness
    • Praticiens bien-être
    • Pharmacie
    • Salon de coiffure
    Trades
    • Bricoleur
    • Matériel informatique et support
    • Systèmes photovoltaïques
    • Cordonnier
    • Services de nettoyage
    • Services CVC
    Autres
    • Organisation à but non lucratif
    • Agence environnementale
    • Location de panneaux d'affichage
    • Photographie
    • Leasing de vélos
    • Revendeur de logiciel
    Browse all Industries
  • Communauté
    Apprenez
    • Tutoriels
    • Documentation
    • Certifications
    • Formation
    • Blog
    • Podcast
    Renforcer l'éducation
    • Programme éducatif
    • Business Game Scale-Up!
    • Rendez-nous visite
    Obtenir le logiciel
    • Téléchargement
    • Comparez les éditions
    • Versions
    Collaborer
    • Github
    • Forum
    • Événements
    • Traductions
    • Devenez partenaire
    • Services for Partners
    • Enregistrer votre cabinet comptable
    Nos Services
    • Trouver un partenaire
    • Trouver un comptable
    • Rencontrer un conseiller
    • Services de mise en œuvre
    • Références clients
    • Assistance
    • Mises à niveau
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Obtenir une démonstration
  • Tarification
  • Aide

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

  • CRM
  • e-Commerce
  • Comptabilité
  • Inventaire
  • PoS
  • Projet
  • MRP
All apps
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Aide

prevent write on status field

S'inscrire

Recevez une notification lorsqu'il y a de l'activité sur ce poste

Cette question a été signalée
contactsres.partnerwrite
4 Réponses
1637 Vues
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
Ignorer
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
Meilleure réponse

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
Ignorer
RacketRebel
Auteur

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
Auteur

the indents are gone, sorry

RacketRebel
Auteur

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
Auteur Meilleure réponse

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
Ignorer
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
Meilleure réponse

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
Ignorer
Avatar
D Enterprise
Meilleure réponse

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
Ignorer
RacketRebel
Auteur

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.

Vous appréciez la discussion ? Ne vous contentez pas de lire, rejoignez-nous !

Créez un compte dès aujourd'hui pour profiter de fonctionnalités exclusives et échanger avec notre formidable communauté !

S'inscrire
Publications associées Réponses Vues Activité
Need help with [v15] ValueError: Invalid field 'total_due' on model 'res.partner' Résolu
contacts res.partner
Avatar
Avatar
1
juin 23
5135
Partner_id name, name
contacts res.partner
Avatar
Avatar
1
juin 22
7882
Make 'opt-out' checkbox settable per each contact of a company (partner)
contacts res.partner
Avatar
0
mars 15
4897
Clickable "Contacts & Addresses" inside res.partner Résolu
contacts res.partner partners
Avatar
Avatar
Avatar
Avatar
Avatar
8
févr. 24
15900
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
août 20
4527
Communauté
  • Tutoriels
  • Documentation
  • Forum
Open Source
  • Téléchargement
  • Github
  • Runbot
  • Traductions
Services
  • Hébergement Odoo.sh
  • Assistance
  • Migration
  • Développements personnalisés
  • Éducation
  • Trouver un comptable
  • Trouver un partenaire
  • Devenez partenaire
À propos
  • Notre société
  • Actifs de la marque
  • Contactez-nous
  • Emplois
  • Événements
  • Podcast
  • Blog
  • Clients
  • Informations légales • Confidentialité
  • Sécurité.
الْعَرَبيّة 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 est une suite d'applications open source couvrant tous les besoins de votre entreprise : CRM, eCommerce, Comptabilité, Inventaire, Point de Vente, Gestion de Projet, etc.

Le positionnement unique d'Odoo est d'être à la fois très facile à utiliser et totalement intégré.

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