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 download all records attachments of sale.order model using button v12

Suscribirse

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

Se marcó esta pregunta
attachmentsodoo12
7 Respuestas
7690 Vistas
Avatar
paidy kumar

when clicking on button in tree view i am getting blank. please somebody help me.


<record model = "ir.ui.view" id = "view_order_form_dbt_task" > 
<field
name = "name" > sale.order.inherit </field>
<field
name = "model" > sale.order </field>
< field
name = "inherit_id" ref = "sale.view_order_form" />
<field
name = "arch" type = "xml" >
<field
name = "payment_term_id"position = "after" >
<field
name ="attachment_ids" />
</field>
</field>
</record>
<record
id = "view_order_tree_dbt_task" model = "ir.ui.view" >
<field
name = "name" > sale.order.tree </field>
<field
name = "model" > sale.order </field>
<field
name = "inherit_id" ref = "sale.view_order_tree" />
<field
name = "arch" type = "xml" >
<field
name = "invoice_status " position = " after " >
<button
name = "action_attachment_down" type = "object" string = "Download" />
</field>
</field>
</record>


in python file
class dbt_task (models.Model): 
    _inherit = 'sale.order'
    attachment_ids = fields.Binary ( 'Attachment' , attachment = True )

    @ api.multi
    def action_attachment_down ( self ):
        for rec in self :
        with io.BytesIO (base64 .b64decode (rec.attachment_ids)) as output:
            result = output.read ()
            base_url = self .env [ 'ir.config_parameter' ] .get_param ( 'web.base.url' )
            attachment_obj = self .env [ 'ir.attachment' ]
            attachment_id = attachment_obj.sudo (). create ({ 'name' : "name" , 'datas_fname' : 'name.file_ext' , 'datas' : result})
            download_url = '/ web / content /' + str (attachment_id.id) + '? download = true '
            return {
            'name' : 'Report' ,
        'type': 'ir.actions.act_url',
         "url": str(base_url) + str(download_url),
        'target': 'new',
            }
    
0
Avatar
Descartar
Sehrish

Get an idea to download file: https://learnopenerp.blogspot.com/2020/06/write-binary-data-nto-zip-file-and-downlaod-it-on-button-click-in-odoo.html

Avatar
Hilar Andikkadavath
Mejor respuesta

Here you are doing .b64decode(rec.attachment_ids) and attachments_ids will be a pool of records but you need a Base64 encoded bytes-like object or ASCII string.

for eg: I am doing like this

content = base64.b64decode(attachment.datas)
headers.append(('Content-Length', len(content)))
response = request.make_response(content, headers)
return response
0
Avatar
Descartar
paidy kumar
Autor

thanks for your response

using below code i am getting only last attachment of my model how do i get all attachments in single pdf. note(all attachments here in pdf format)

my code:

def action_attachment_down(self):

sale_orders = self.env['sale.order'].search([])

result = b' '

for rec in sale_orders:

if rec.attachment_ids:

result.write(rec.attachment_ids)

_logger = logging.info("record id Here.........................")

_logger = logging.info(rec.id)

base_url = self.env['ir.config_parameter'].get_param('web.base.url')

attachment_obj = self.env['ir.attachment']

attachment_id = attachment_obj.sudo().create(

{'name': "name", 'datas_fname': 'sale_attachments.pdf', 'datas': result})

download_url = '/web/content/' + str(attachment_id.id) + '?download=true'

return {

'name': 'Report',

'type': 'ir.actions.act_url',

'url': str(base_url) + str(download_url),

'target': 'new',

}

Hilar Andikkadavath
Great, please check the http route defined for making this download response in class binary, that is web, controllers, main.py, class binary. 
You will get more detailed view here

On Wed, 12 Aug 2020, 4:52 pm paidy kumar, <mpaidykumar@gmail.com> wrote:

thanks for your response

using below code i am getting only last attachment of my model how do i get all attachments in single pdf. note(all attachments here in pdf format)

my code:

def action_attachment_down(self):

sale_orders = self.env['sale.order'].search([])

result = b' '

for rec in sale_orders:

if rec.attachment_ids:

result.write(rec.attachment_ids)

_logger = logging.info("record id Here.........................")

_logger = logging.info(rec.id)

base_url = self.env['ir.config_parameter'].get_param('web.base.url')

attachment_obj = self.env['ir.attachment']

attachment_id = attachment_obj.sudo().create(

{'name': "name", 'datas_fname': 'sale_attachments.pdf', 'datas': result})

download_url = '/web/content/' + str(attachment_id.id) + '?download=true'

return {

'name': 'Report',

'type': 'ir.actions.act_url',

'url': str(base_url) + str(download_url),

'target': 'new',

}

Envoyé par Odoo S.A. utilisant Odoo.

paidy kumar
Autor

for this i need to merge all attachments in single byte array.

but i am not able to do this do you have any idea to do this

Hilar Andikkadavath

Sorry, I can't check right now, but you can do one thing, zip all attachments and pass zip file in response. I will test tomorrow for other methods and will give you the feedback.

paidy kumar
Autor

Thanks hilar thankyou so much.

¿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
Creating Attachments For account.invoice in odoo 12? Resuelto
attachments ir.attachment odoo12
Avatar
1
ene 23
10207
Attach documents to products in website in odoo 12? Resuelto
attachments website odoo12
Avatar
Avatar
1
nov 19
3617
Can't affect attachments to specific records of a custom module through XML-RPC
xmlrpc attachments odoo12
Avatar
0
abr 19
4081
Attachements
attachments
Avatar
0
dic 24
2236
Odoo Mail Sending Limit Resuelto
odoo12
Avatar
Avatar
Avatar
2
dic 23
16278
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.

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