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

Many2one in form view - Odoo 18

Suscribirse

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

Se marcó esta pregunta
2 Respuestas
3261 Vistas
Avatar
Boris Giordanengo

Hello,

I have a model like this:

class Main(models.Model):
_name ='main'

name = fields.Char(string='Name')
relation_id = fields.Many2one(string='Relation', comodel_name='relation')

I have one 'relation' record for each 'main' record.

Of course, I can merge the two tables.
But it is possible to have a XML file like this which create the 'main' record as well as the 'relation' record at the same time ?
<odoo>

<record id="my_id" model="ir.ui.view">
<field name="name">main.form.view</field>
<field name="model">main</field>
<field name="type">form</field>
<field name="arch" type="xml">
<form>
<sheet>
​ ​<group>
​ ​<field name="name"/>
​ ​</group>
​ ​ ​<notebook>
​ ​ ​ ​<page string="relation">
<field name="relation_id">
<form>
<field name="name_relation"/>
<field name="second_field"/>
</form>
</field>
​ ​ ​</page>
</notebook>
</sheet>
</form>
</field>
</record>

</odoo>

Thanks in advance,

Boris

0
Avatar
Descartar
Christoph Farnleitner

Can your nested form node not just simply become a list? I don't really get what you are trying to achieve with this setup, hence also can't tell you what you may do for the moment.

Boris Giordanengo
Autor

Christoph Farnleitne ,I merge the two table and solve my problem.


Avatar
Piyush H
Mejor respuesta

Problem

You want to create both a main record and its linked relation record in one form view, without merging the models.

Your current XML tries to embed a <form> inside a <field>, which isn't valid Odoo syntax.

Correct Approach

Use inline editing with the options attribute on the many2one field. Here’s how:

1. Update Your XML View

xml

<record id="view_main_form" model="ir.ui.view">
    <field name="name">main.form.view</field>
    <field name="model">main</field>
    <field name="arch" type="xml">
        <form>
            <sheet>
                <group>
                    <field name="name"/>
                </group>
                <notebook>
                    <page string="Relation">
                        <field name="relation_id" 
                               options="{'no_open': True, 'no_create': False}"
                               context="{'form_view_ref': 'your_module.view_relation_form'}"/>
                    </page>
                </notebook>
            </sheet>
        </form>
    </field>
</record>
2. Create a Separate Form View for relation

Define a simplified form for quick creation:

xml

<record id="view_relation_form" model="ir.ui.view">
    <field name="name">relation.popup.form</field>
    <field name="model">relation</field>
    <field name="arch" type="xml">
        <form>
            <group>
                <field name="name_relation"/>
                <field name="second_field"/>
            </group>
        </form>
    </field>
</record>

3. Key Attributes Explained

  • options="{'no_open': True}": Prevents opening the full record view.
  • no_create: Set to False to allow new record creation.
  • context="{'form_view_ref': ...}": Forces the popup to use your custom form.
Alternative: Default Values

If you always want to auto-create a relation when creating a main record:

1. Override create in main model

python

@api.model
def create(self, vals):
    if not vals.get('relation_id'):
        relation = self.env['relation'].create({
            'name_relation': vals.get('name') + " Relation",
            'second_field': "Default Value",
        })
        vals['relation_id'] = relation.id
    return super().create(vals)
Result

Now when you:

  1. Create a new main record,
  2. Click the relation_id field,
  3. Select "Create and Edit",
  4. A popup with your custom relation form appears.

After saving both forms, the records are linked automatically.

Why This Works
  • Odoo’s many2one field natively supports inline creation.
  • The options and context attributes control the behavior.
  • No need for nested <form> tags (which aren’t supported).

🚀 Did This Solve Your Problem?

If this answer helped you save time, money, or frustration, consider:

✅ Upvoting (👍) to help others find it faster

✅ Marking as "Best Answer" if it resolved your issue

Your feedback keeps the Odoo community strong! 💪

(Need further customization? Drop a comment—I’m happy to refine the solution!)

0
Avatar
Descartar
Avatar
srikesh infotech
Mejor respuesta

In Odoo, a Many2one field by default shows as a dropdown list with a search option. However, when we define a nested <form> inside a <field name="relation_id"> (like in your example), Odoo shows the linked record in a form view, allowing users to create or edit the related record directly from the main form.

When you open the Many2one field in the UI, Odoo shows a mini form with all the fields of the related model.

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

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

Inscribirse
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