Ir al contenido
Odoo Menú
  • Inicia sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Inteligencia artificial
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de propiedades
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Comunidad
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda
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

trying to auto correct a wrong users value

Suscribirse

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

Se marcó esta pregunta
onchange
1 Responder
4067 Vistas
Avatar
Gondran Louis

Hi, in this program, I'm trying to automatically correct a value if the user uses the wrong syntax, for example, if they enter '12h12,' I'd like to auto-correct it to '12:12.' Even though the corrected_value is modified correctly, it's not returned in my ERP, which retains the incorrect value. So, I assume the error comes from the following two lines: value = corrected_value self.write({field_name: value})

How can I fix this?"



# -*- coding: utf-8 -*-

import json

from openerp.exceptions import except_orm, ValidationError, Warning

from openerp import models, fields, api, _


import requests

import re


class x_days(models.Model):

  _name = 'x.days'

  name = fields.Char(string='Breaks', copy=False)

  breaks_monday = fields.Char(string='Monday breaks')

  breaks_tuesday = fields.Char(string='Tuesday breaks')

  breaks_wednesday = fields.Char(string='Wednesday breaks')

  breaks_thursday = fields.Char(string='Thursday breaks')

  breaks_friday = fields.Char(string='Friday breaks')


  def config(self):

    get_rcdst = self.search([])

    mon = get_rcdst.read(['breaks_monday'])

    tue = get_rcdst.read(['breaks_tuesday'])

    wed = get_rcdst.read(['breaks_wednesday'])

    thu = get_rcdst.read(['breaks_thursday'])

    fri = get_rcdst.read(['breaks_friday'])

    d = {'fri': [], 'mon': [], 'tue': [], 'thu': [], 'wed': []}

    l = [mon, tue, wed, thu, fri]

    for i in mon:

      d['mon'].append(i['breaks_monday'])

    for i in tue:

      d['tue'].append(i['breaks_tuesday'])

    for i in wed:

      d['wed'].append(i['breaks_wednesday'])

    for i in thu:

      d['thu'].append(i['breaks_thursday'])

    for i in fri:

      d['fri'].append(i['breaks_friday'])


    d = json.dumps(d)

    headers = {'Content-Type': 'application/json'}

    response = requests.post('http://172.19.0.35:5000/new_slot', data=d, headers=headers)


    if response.status_code == 200:

      print('Requête POST réussie')

      print('Réponse du serveur:', response.text)

    else:

      print('Échec de la requête POST')

      print('Code d état HTTP:', response.status_code)

    return 0


  @api.multi

  def write(self, vals):

    rc = super(x_days, self).write(vals)

    self.config()

    return rc


  @api.model

  def create(self, vals):

    rc = super(x_days, self).create(vals)

    self.config()

    return rc


  @api.onchange('breaks_monday', 'breaks_tuesday', 'breaks_wednesday', 'breaks_thursday', 'breaks_friday')

  def _onchange_my_field(self):

      for field_name in ['breaks_monday', 'breaks_tuesday', 'breaks_wednesday', 'breaks_thursday', 'breaks_friday']:

          value = getattr(self, field_name)

          if value:

              pattern = r'^\d{2}:\d{2}$'  # Syntaxe correcte "hh:mm"

              if not re.match(pattern, value):

                  corrected_value = self._try_to_correct_value(value)

                  if corrected_value:

                      value = corrected_value

                      self.write({field_name: value})

                  else:

                      raise ValidationError("Syntaxe incorrecte. Utilisez hh:mm.")

                      return 0



  def _try_to_correct_value(self, value):

    corrected_value = None

    if ',' in value:

        corrected_value = value.replace(',', ':')

    elif 'h' in value:

        corrected_value = value.replace('h', ':')

    return corrected_value


0
Avatar
Descartar
Avatar
Savya Sachin
Mejor respuesta

Hi,

Just try updating the following line of code 

​ value = corrected_value 

​self.write({field_name: value})

like this,

​self[field_name] = corrected_value

Thanks


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

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

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
"Wrong value for %s: %r" % (self, value) Resuelto
onchange
Avatar
Avatar
2
oct 23
4337
How to add domain in onchange function for a One2many field Resuelto
onchange
Avatar
Avatar
Avatar
2
ago 23
6601
How to create dynamic domain on many2one fields with onchange function? Resuelto
onchange
Avatar
Avatar
Avatar
Avatar
Avatar
4
ago 23
23375
Odoo onchange method is not saving values in readonly fields Resuelto
onchange
Avatar
Avatar
Avatar
Avatar
3
oct 22
13845
How to add records to one2many field using onchange event Resuelto
onchange
Avatar
Avatar
Avatar
Avatar
3
mar 22
39561
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • 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 Svenska ภาษาไทย 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 estar totalmente integrado.

Sitio web hecho con

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