Ir al contenido
Odoo Menú
  • Iniciar 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
    • Aprobaciones
    • 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 bienes inmuebles
    • 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
  • Odoo Community
    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

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • 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 Solve : AttributeError: 'str' object has no attribute 'datas'

Suscribirse

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

Se marcó esta pregunta
errorodooV8strattribute_erroroldAPI
5 Respuestas
169209 Vistas
Avatar
Ahmed Ramzy
def onchange_get_datas(self, cr, uid, ids, image_logo_attachment_id, context=None):
# import pdb;pdb.set_trace()
if image_logo_attachment_id:
image_logo_datas = image_logo_attachment_id.datas
else:
image_logo_datas = False

return {'value':{'image_logo_datas':image_logo_datas}}

This is my cod ^

and the fields are :

'image_logo_attachment_id': fields.many2one('ir.attachment', 'Image logo attachment',
help='Technical field to store image in filestore'),
'image_logo_datas': fields.related('image_logo_attachment_id', 'datas', type='binary',
string='Image logo datas', Class=".oe_avatar"),

0
Avatar
Descartar
Axel Mendoza

please provide us the xml view field definition to check the onchange arguments to provide you with a full answer

Ahmed Ramzy
Autor

<field name="image_logo_datas" nolabel="1" widget='image' class="oe_avatar" on_change="onchange_get_datas(image_logo_datas)"/>

Avatar
Axel Mendoza
Mejor respuesta

Hi Ahmed

** Update: this is the original answer for use an onchange for the datas field from the attachment

The onchange need to be defined for the field image_logo_attachment_id in the view like:

<field name="image_logo_attachment_id" on_change="onchange_get_datas(image_logo_attachment_id)"/>

And the onchange definition in python need to be as follow:

def onchange_get_datas(self, cr, uid, ids, image_logo_attachment_id, context=None):
if image_logo_attachment_id:
image_logo_datas = self.pool.get('ir.attachment').browse(cr, uid, image_logo_attachment_id).datas
else:
image_logo_datas = False

return {'value':{'image_logo_datas':image_logo_datas}}

****

** Update: For using directly related fields to create an attachment:

class custom_class(models.Model):
    _name = 'custom.module'

    _columns = {
        'image_logo_attachment_id': fields.many2one(
            'ir.attachment', 
            string='Image logo attachment',
            help='Technical field to store image in filestore'
        ),
        'image_logo_datas': fields.related(
            'image_logo_attachment_id', 
            'datas', 
            type='binary',
            string='Image logo datas' 
        ),
        'image_logo_datas_fname': fields.related(
            'image_logo_attachment_id', 
            'datas_fname', 
            type='char',
            string='Image logo fname'
        )
    }

    def create(self, cr, uid, vals, context=None):
        if vals.get('image_logo_datas', False) and vals.get('image_logo_datas_fname', False):
            attach_id = self.pool.get('ir.attachment').create(cr, uid, {
                'name': vals.get('image_logo_datas_fname'),
                'datas_fname': vals.get('image_logo_datas_fname'),
                'datas': vals.get('image_logo_datas')
            }, context=context)
            vals['image_logo_attachment_id'] = attach_id
        res = super(custom_class, self).create(cr, uid, vals, context=context)
        return res
    
    def write(self, cr, uid, ids, vals, context=None):
        if vals.get('image_logo_datas', False) and vals.get('image_logo_datas_fname', False):
            for elem in self.browse(cr, uid, ids, context=context):
                if not elem.image_logo_attachment_id:
                    attach_id = self.pool.get('ir.attachment').create(cr, uid, {
                        'name': vals.get('image_logo_datas_fname'),
                        'datas_fname': vals.get('image_logo_datas_fname'),
                        'datas': vals.get('image_logo_datas')
                    }, context=context)
                    elem.write({'image_logo_attachment_id': attach_id})
        res = super(custom_class, self).write(cr, uid, ids, vals, context=context)
        return res

and use it like this in the view:

<field name="image_logo_datas" filename="image_logo_datas_fname" widget='image' class="oe_avatar"/>
<field name="image_logo_datas_fname" invisible="1"/>

For the future, make sure that you provide all the code that you have to make it better to fix it and use the same references and objects names. Provide better descriptions of the situation and what you are trying to do, don't let anything out.

That make it easy to answer questions.  

**

0
Avatar
Descartar
Ahmed Ramzy
Autor

but i don't have this field in the view because i'm uploading the image from field 'image_logo_datas' (related field) ?

Axel Mendoza

check the answer update

Avatar
Mohammed Amal N
Mejor respuesta

Hello,

It looks like field image_logo_attachment_id is a str and not record.

How are you passing variable image_logo_attachment_id to your function. Please share how you call the method onchange_get_datas.

0
Avatar
Descartar
Ahmed Ramzy
Autor

<field name="image_logo_datas" nolabel="1" widget='image' class="oe_avatar" on_change="onchange_get_datas(image_logo_datas)"/>

¿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
How to access sale.order fields from sale.order.line onchange?
odooV8 oldAPI
Avatar
1
feb 20
1560
KeyError : u'wc.backend'
error odooV8
Avatar
0
oct 15
4552
[Solved]Error when uninstalling and installing - Odoo 8 Resuelto
error odooV8
Avatar
2
may 15
5615
have an internal server error in odoo?????????
error odooV8
Avatar
Avatar
1
mar 15
4478
NotImplementedError: '__setitem__' not supported on frozendict Resuelto
error context odooV8
Avatar
Avatar
Avatar
Avatar
9
jul 25
18951
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 ภาษาไทย 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