Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • eLearning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Información
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Food & Hospitality
    • Bar y taberna
    • Restaurante
    • Comida rápida
    • Guest House
    • Distribuidor de bebidas
    • Hotel
    Real Estate
    • Real Estate Agency
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consulting
    • Accounting Firm
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Trades
    • Handyman
    • Hardware y asistencia informática
    • Solar Energy Systems
    • Zapatero
    • Servicios de limpieza
    • HVAC Services
    Others
    • Nonprofit Organization
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Browse all Industries
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Services for Partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

prevent write on status field

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
contactsres.partnerwrite
4 Respuestas
1620 Vistas
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
Descartar
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
Mejor respuesta

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
Descartar
RacketRebel
Autor

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
Autor

the indents are gone, sorry

RacketRebel
Autor

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
Autor Mejor respuesta

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
Descartar
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
Mejor respuesta

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
Descartar
Avatar
D Enterprise
Mejor respuesta

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
Descartar
RacketRebel
Autor

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.

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
Need help with [v15] ValueError: Invalid field 'total_due' on model 'res.partner' Resuelto
contacts res.partner
Avatar
Avatar
1
jun 23
5118
Partner_id name, name
contacts res.partner
Avatar
Avatar
1
jun 22
7866
Make 'opt-out' checkbox settable per each contact of a company (partner)
contacts res.partner
Avatar
0
mar 15
4895
Clickable "Contacts & Addresses" inside res.partner Resuelto
contacts res.partner partners
Avatar
Avatar
Avatar
Avatar
Avatar
8
feb 24
15884
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
ago 20
4523
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

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