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
    Alimentación y hostelería
    • Bar y taberna
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y asistencia informática
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • 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 upload multiple file in website, and add it as an attachment to a new record?

Suscribirse

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

Se marcó esta pregunta
attachmentcontrollerwebsite
3 Respuestas
22662 Vistas
Avatar
Luis Angel Bautista Molina

Hi there,

Has anybody tried to upload multiple file from the Odoo website, and then call a controller with method post to create a record and save the attachment?

 The input type file in my template view

<div class="form-group row form-field o_website_form_required_custom">
                                <div class="col-md-4 col-sm-3 text-right">
                                    <label class="control-label" for="project_managment"></label>
                                </div>
                                <div class="col-md-6 col-sm-7">
                                    <input type="file" name="attachment" class="file" multiple="true" data-show-upload="true" data-show-caption="true" lass="file" data-show-preview="true"/>
                                </div>
                            </div>

in my controller

@http.route(['/upload/file/<model("model.custom"):object>/<model("model.custom2"):object2>/confirm'],type='http',auth='user',website=True)
    def convocatoria_proyecto_info(self, convocatoria, proyecto, **kwargs):
        values = {}
        if kwargs.get('attachment',False):
            Attachments = request.env['ir.attachment']
            name = kwargs.get('attachment',False).filename     
            file = kwargs.get('attachment',False)          
            project_id = proyecto.id
            attachment = file.read()
            attachment_id = Attachments.sudo().create({
                'name':name,
                'datas_fname': name,
                'res_name': name,
                'type': 'binary',  
                'res_model': 'model.model',
                'res_id': project_id,
                'datas': base64.b64encode(attachment),
            })
            values = {'attachment' : attachment_id}
            return request.render("modulename.template_to_render", value)

Could anybody tell me in which format I should pass the multiple value, how to get & pass attach it as an attachment on the just create record?

Regards

1
Avatar
Descartar
Sehrish

Try this one: http://learnopenerp.blogspot.com/2019/01/add-attachement-file-from-odoo-website.html

Samo Arko

@Sehrish at least read the title! It says MULTIPLE files!!!

I'm having the same problem with multiple files. The problem is that you have only one file in your post variable. If you could get the files in a list you just call the create method in "for attachment in post.get(attachment)"

Avatar
Samo Arko
Mejor respuesta

For uploading multiple files you need to have set the proper enctype in your form tag and have the option for multiple files in your input tag.

<form method="post" class="s_website_form" action="/new-ticket" enctype="multipart/form-data">
    <p><strong>Attachment </strong><input type="file" name="task_attachment" multiple="true"/></p>
</form>

In your controller you need to use request.httprequest.files.getlist() to get the files and just store them with a for loop.

if request.httprequest.method == 'POST':
        # ... # code that creates and fills a dictonary with validated data # ... new_task = request.env['project.task'].sudo().create(create_dict) if 'task_attachment' in request.params: attached_files = request.httprequest.files.getlist('task_attachment') for attachment in attached_files: attached_file = attachment.read() request.env['ir.attachment'].sudo().create({ 'name': attachment.filename, 'res_model': 'project.task', 'res_id': new_task.id, 'type': 'binary', 'datas_fname': attachment.filename, 'datas': attached_file.encode('base64'), })  

It's sad that something so basic for websites isn't better documented. I needed to analyze the whole http.py and go trough the wergzeug documentation to find the methods to get it working. 

7
Avatar
Descartar
COULIBALY Zana Dramane

It works fine for me. Thank you very much!

Samo Arko

Nice... no problem.

¿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
Add Attachement From website. Resuelto
attachment website
Avatar
Avatar
2
feb 24
26379
How to get the current user id from an Odoo Website Web Controller ? Resuelto
controller website odoo
Avatar
Avatar
2
dic 21
25209
Odoo bind custom website layout to model
controller website 13
Avatar
0
ene 21
3014
Download pdf file on ir_attachment from other application Resuelto
pdf attachment controller
Avatar
Avatar
1
ago 20
9836
inherit the home controller odoo 13
controller website Odoo13.0
Avatar
2
jul 20
5010
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