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

Change filename of binary field

Suscribirse

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

Se marcó esta pregunta
v7model
12 Respuestas
25836 Vistas
Avatar
Vitaliy

I have in my model function filed returning binary. How can I change returning filname?

Function:

def _get_vcard(self, cr, uid, ids, prop, unknow_none, context=None):
            res = []
            for id in ids:
                res.append((id, base64.b64encode("test".encode('utf-8'))))
            return dict(res)

Model:

 _columns = {
        'vcard': fields.function(_get_vcard, type='binary', string='vCard')
    }
3
Avatar
Descartar
Avatar
Alexander
Mejor respuesta

Hi, try to use something like this:

py file:

_columns = {
    'vcard_stream': fields.binary('File Stream', readonly=True),
    'vcard_name': fields.char('File name', 40, readonly=True),
}

_defaults = {
    'vcard_name': 'your_filname.vcard',
}

xml file:

<field name="vcard_stream" string="File Stream" filename="vcard_name"/>
3
Avatar
Descartar
Prakash

Hi Alexandar, I followed the same steps in my custom module but download file name always shows Model name used in the xml File For example Download file name shows "model_name" <field name="model">model.name</field> Not downloaded with defined _defaults file name. Any idea? How to fix this issue. Thanks

Alexander

Hi. Can you show your source code? Perhaps you missed something.

Prakash

Updated the source code

Abhishek H Menon

I have also done the same thing above, but I did not get the result. The name is shown as a pdf extension but, it is downloaded/opened as binary file which has no extension. How we can embedd the extension along with the file generation?

Avatar
Sarender Reddy
Mejor respuesta

Use like below in xml file.

as per Odoo11 


<field widget="binary" name="datas" filename="datas_fname"/>

                  <field name="datas_fname" readonly = "1" invisible="1"  force_save="1"/>


Get the uploaded file in py file.


curr_obj = self  

        if not curr_obj.datas:

            raise UserError(_('Please Choose The File!'))

        file_name = curr_obj.datas_fname

        print "curr_obj.datas_fname here",curr_obj.datas_fname

        print "file namr here",file_name

        fname = str(file_name.split('.')[1])

        if fname != 'xls':

            raise UserError(_('Please Choose The File With .xls extension and proper format!'))

        try:

            val=base64.decodestring(curr_obj.datas)

            fp = StringIO.StringIO()

            fp.write(val)     

            wb = xlrd.open_workbook(file_contents=fp.getvalue())

            wb.sheet_names()

            sheet_name=wb.sheet_names()

            sh = wb.sheet_by_index(0)

            sh = wb.sheet_by_name(sheet_name[0])

            n_rows = sh.nrows

2
Avatar
Descartar
Avatar
Aurelien
Mejor respuesta

Hi Vitaly!

The answer posted by Prakash should work fine, i would just change this part 

<group>

<field name="edi_filename"/>

<field name="edi_data" filename="edi_filename"/>

</group>

to  

<group>

<field name="edi_filename" invisible='1'/>

<field name="edi_data" filename="edi_filename"/>

</group>


Because filename already shows up following Download in your view and as this is "readonly" you do really need to display it two times.

But with the code you're showing above i am not sure if the previous answers reached your expectation.

I advise you to go to have a look on the ir.attachment model in the Base module of odoo. You will find all the answer you want to find there.

However, you will indeed need a field filename in order to have a name (plus an extension?) to your downloaded file. 

1
Avatar
Descartar
Avatar
Prakash
Mejor respuesta

In Wizard using the below code

Python File

_columns = {
        'edi_data': fields.binary('File Stream', readonly=True),
        'edi_filename': fields.char('File Name', size=32, readonly=True),
        }



_defaults = {
   'edi_filename': 'Invoice.txt',
 }

XML File

<field name="arch" type="xml">
            <form string="Form">
                <group>
                    <field name="edi_filename"/>
                    <field name="edi_data" filename="edi_filename"/>
             </group>
0
Avatar
Descartar
Alexander

As far as I know "name" is something like function word. Try to rename fields. Also _defaults = { 'name': 'Invoice.txt', } should be in py file.

Alexander

I don't know. My example works. Try to use it without any changes first. Maybe _stream and _name are "magic" words.

Prakash

Can you please post your web\controllers\main.py File saveas_ajax Method code i think in my case issues in that file. I am using latest version 7 but still issues. Thanks

Abhishek H Menon

In my case, it is a wizard which has a readonly binary field for storing file, and I am getting the file, but when I suppose to download it, it is getting downloaded as a binary file which has no specific extension. I need the file in pdf. Can anyone please suggest a way to do that?

¿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
Duplicate all the project model
v7 model
Avatar
Avatar
Avatar
2
mar 15
7996
How to execute function immediately after adding new record?
v7 model
Avatar
Avatar
1
mar 15
9664
Get notebook current tab string and save it to my model
v7 tabs model
Avatar
Avatar
1
mar 15
4844
How to add a "Delete" button on the popup form? Resuelto
v7
Avatar
Avatar
1
oct 25
5885
Minimum Lot Charge For Sales Order Line Items
v7
Avatar
0
dic 24
10680
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