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

How to make email on res.partner be unique

Suscribirse

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

Se marcó esta pregunta
emailconsultantValidationErrorUniqueConstraintv14
2 Respuestas
5858 Vistas
Avatar
Tri Nanda

I using Odoo14,


I create a new custom model that inherit email field from res.partner, and want to make email for each of my users which is students be unique.


Here is my snipet of code:


class AqurStudent(models.Model):
_name = "aqur.student"
_description = "AQUR Student"
_inherit = ['mail.thread', 'mail.activity.mixin']
_inherits = {"res.partner": "partner_id"}
partner_id = fields.Many2one('res.partner', 'Partner', required=True, ondelete="cascade")

@api.constrains('email')
def _check_email(self):
for record in self:
if record.email == record.email:
raise ValidationError('The email already registered, please use another email!')

res_partner = self.env['res.partner'].search_count([('email', '=', self.email)])
if len(res_partner) > 1:
raise ValidationError('The email already registered, please use another email!')

_sql_constraints = [
('email_key', 'UNIQUE (email)', 'The email already registered, please use another email!')
]
The code above seems doesn't have any effect, I still can duplicate my students email and doesn't raise  a ValidationError.


So,  whats  wrong  with  my  code  above?

Please,  any  help,  source  or  tutorial  how  to  face  this  will  be  very  thanks,


Thanks,

Tri  Nanda 

0
Avatar
Descartar
Avatar
Tri Nanda
Autor Mejor respuesta

Finanly I solved this isue using this following code:

class Partner(models.Model):
_inherit = "res.partner"

@api.constrains('email')
def _check_email(self):
count_email = self.search_count([('email', '=', self.email)])
if count_email > 1 and self.email is not False:
raise ValidationError('The email already registered, please use another email!')

I don't find the way yet, how to use constrains on inherit model, so then I create the constrains code on the model that store the email field directly.


Thanks,

Tri Nanda


0
Avatar
Descartar
Avatar
Md. Saif Islam
Mejor respuesta

You can use the code as below,

@api.model
def create(self, vals):
    previous_email = self.env['aqur.student'].search([('email','=',vals['email'])])
    if len(previous_email) >= 1:         raise ValidationError(_("This Email is Already Taken"))


Try to follow the above techniques, i hope this will solve your issue.



1
Avatar
Descartar
¿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
ValidationError
ValidationError v14
Avatar
Avatar
1
oct 22
10672
Odoo 14: Unique values but how to prevent with spelling mistakes
UniqueConstraint v14
Avatar
Avatar
Avatar
2
ene 24
5447
Odoo Out Mails in Spam Filter
email spam v14
Avatar
0
jul 23
2797
Use automated action to send low stock email notification
email notifications v14
Avatar
Avatar
1
ago 22
5035
Odoo 14, how to link job application form with the job's survey questions, so that applicant can fill the survey after applying for the job.
email recruitment v14
Avatar
0
feb 22
3943
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