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 create .DAT file?

Suscribirse

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

Se marcó esta pregunta
1 Responder
12997 Vistas
Avatar
Anirudh Lou

Hi every one. My question is, somehow, related to my previous question. How can i create .DAT, .csv, .ods, or even .xls , so that user can have a softcopy of the files. For example, user want to have the copy of list of all pupils in a .DAT then he can download it. Any one can help?

----------------------------

EDIT

Thank you sir for your answer, actually i did what you have told me, but i got an error, or perhaps my code is far way from reality. I made a class named 'file.holder' just like this one:


class file_holder(osv.osv):

_name = 'file.holder'

_columns = { 'name' : fields.char('File name'),
                       'file_data' : fields.binary('File Name',filters='*.DAT',)
                     }

def get_file(self, cr, uid, context=None):

       file_path = addons.get_module_resource('mp_seven', 'files', 'studentlist.DAT')

       fo = {} fo = open(file_path,"wb")

      active_id = self.pool.get('student.student').search(cr,uid,[])

      for list in self.browse(cr,uid,active_id,context=context):

            fo.write(list.id+","+list.name) self.create(cr,uid,{ 'name' : '', 'file_data' : file_path })

      return fo.read().encode('base64')

file_holder()

 

where addons is a folder in openerpserver-7, mp_seven is my project name, files is subfolder in my project and where studentlist.DAT resides. Whenever this method is bieng called in other class the browser/terminal says :

             file_path = addons.get_module_resource('mp_seven', 'files', 'studentlist.DAT')

NameError: global name 'addons' is not defined

 

 

 

------------------------------------------------------------------------

RE EDIT:

 

Sir, this is how i implement your pseudo code, but my problem now is that my return view doesn't show anything (on my file.holder class):

 

def file_writer(self, cr, uid, ids, context=None):

        virtual_file = StringIO.StringIO()

        student_object = self.pool.get('student.student')

        active_id = student_object.search(cr,uid,[])

        for obj_list in student_object.browse(cr,uid,active_id,context=context): 

                  virtual_file.write(str(obj_list.last_name)+","+str(obj_list.first_name)+","+str(obj_list.middle_name))

                  self.create(cr,uid,{ 'name' : 'studentList.DAT', 'file_data' : virtual_file })

        return { 'type': 'ir.actions.act_window',

                      'res_model': 'file.holder',

                      'view_mode': 'form',

                     'view_type': 'form',

                     'views': [(False, 'form')],

                     'target': 'new', }

 

this is how i called it in my "student.student" class

 

def call_file_writer(self,cr,uid,ids,context=None):

return self.pool.get('file.holder').file_writer(cr,uid,ids,context=context)

 

 

def loadstudent(self,cr,uid,ids,context=None):

.....

return self.call_file_writer(cr, uid, ids, context=context)

 

When the view is rendered, it shows only the two fields without it's object.

 

 

2
Avatar
Descartar
Avatar
Ludo - 21South
Mejor respuesta

In my previous answer I explained to you how to create files in python:

https://www.odoo.com/forum/help-1/question/how-to-create-a-file-and-save-data-on-it-66983

In addition to this, you can also create a binary field in Odoo. If you create this field, you will allow everyone to attach files to the record the field is on. Make the file readonly for your users in order for them not to upload anything new. When creating the record for example (or when pressing save) create one of the previously mentioned virtual files and use its base64 value as value for this field. This will allow you to generate files and make them available for download by your users.

------------------

EDIT

I believe you did not quite understand what I meant. Something in the likes of the following should help you out:

  • import stringio (default python lib)
  • Then create an instance of StringIO (somefile = StringIO())
  • No need for path and such. Just edit as though it was a regular file. (somefile.write("All my contents go here"))
  • When you have that file in memory, write its contents directly to the field in your OpenERP instance. ( self.pool.get(file.holder').create(cr, uid, {'name': 'My super file', 'my_binary_field': somefile)}
  • Mind you, this is PSEUDO CODE, not real interpretation. 
2
Avatar
Descartar
Anirudh Lou
Autor

Thank you sir for your answer, actually i did what you have told me, but i got an error, or perhaps my code is far way from reality. I made a class named 'file.holder' just like this one: class file_holder(osv.osv): _name = 'file.holder' _columns = { 'name' : fields.char('File name'), 'file_data' : fields.binary('File Name',filters='*.DAT',) } def get_file(self, cr, uid, context=None): file_path = addons.get_module_resource('mp_seven', 'files', 'studentlist.DAT') fo = {} fo = open(file_path,"wb") active_id = self.pool.get('student.student').search(cr,uid,[]) for list in self.browse(cr,uid,active_id,context=context): fo.write(list.id+","+list.name) self.create(cr,uid,{ 'name' : '', 'file_data' : file_path }) return fo.read().encode('base64') file_holder() where addons is a folder in openerpserver-7, mp_seven is my project name, files is subfolder in my project and where studentlist.DAT resides. Whenever this method is bieng called in other class the browser/terminal says : file_path = addons.get_module_resource('mp_seven', 'files', 'studentlist.DAT') NameError: global name 'addons' is not defined

Ludo - 21South

Hi anirudh. Please update your initial question with the code above. Currently it is unreadable for us.

Anirudh Lou
Autor

sir i have modify the above comment here is the link for the above: https://www.odoo.com/forum/help-1/question/create-files-67330

Ludo - 21South

You Created a new question, which was not the purpose of my answer. I deleted the question and edited this current question. I will update my answer.

Anirudh Lou
Autor

Thank you very much sir for your help, it really works. I have seen the file being created in my database. Since you have helped me, can i ask bonus help? How can i make the file downloadable? I mean, The button w/c is responsible for the file creation is named 'Create .DAT file'. Now at the same time, i want that the download pop up message appears automatically. Is it possible to do it?

Ludo - 21South

You are very welcome. I think your best bet is to provide a certain tag in the XML view. I believe it is class="oe_link". That should create a link out of the file, like you would with the tag in regular HTML.

Anirudh Lou
Autor

Do you mean sir, i'll put class="oe_link" on my button? just like this one: . I did this but nothing popped up, but it persist on the database.

Ludo - 21South

Hehe, no I meant on the binary field in the XML. That way instead of showing the buttons, it will just create a link out of the file. I do not know of a way to present a dialog to the user right after creating the file, so this would be my alternative.

Anirudh Lou
Autor

Hmp? Do you mean sir, i'll put class="oe_link" on file_data in xml view? Sir, i have no view for my file.holder class. Actually, my project would behave like this, In my student list view i created 'Create .DAT file' button that calls file_writer method in my 'file.holder' class. My aim is that when user clicks that butoon, the system will show/allow the user to download the .DAT file. Just like how Print sidebar behave.

Anirudh Lou
Autor

I am not so sure, if it involves javascript manipulation.

Ludo - 21South

I'm sorry but I can't help you with that. I see now that my recommendation does not work in your case. Javascript is not my strong point here. The only thing I can image to try is using the button to open a view itself for the 'file.holder' class. This can be a temporary view and pre filled, but I'm not sure that fits your business needs. Good luck!

Anirudh Lou
Autor

Nope sir, you really help me and it is a big addition on my knowledge in openerp and in python and I must thank you for that. I feel that i am indebited to you. :) Although, i was not able to make it now but hopefully someday i'm gonna make it. Thanks a lot sir.

Ludo - 21South

You are very welcome. If you manage to get the answer to your question, don't hesitate to update the question and show the others on the board what it was.

Anirudh Lou
Autor

Sir, this is how i implement your pseudo code, but my problem now is that my return view doesn't show anything: def file_writer(self, cr, uid, ids, context=None): virtual_file = StringIO.StringIO() student_object = self.pool.get('student.student') active_id = student_object.search(cr,uid,[]) for obj_list in student_object.browse(cr,uid,active_id,context=context): virtual_file.write(str(obj_list.last_name)+","+str(obj_list.first_name)+","+str(obj_list.middle_name)) self.create(cr,uid,{ 'name' : 'studentList.DAT', 'file_data' : virtual_file }) return { 'type': 'ir.actions.act_window', 'res_model': 'file.holder', 'view_mode': 'form', 'view_type': 'form', 'views': [(False, 'form')], 'target': 'new', } this is how i called it in my "student.student" class def call_file_writer(self,cr,uid,ids,context=None): return self.pool.get('file.holder').file_writer(cr,uid,ids,context=context) def loadstudent(self,cr,uid,ids,context=None): ..... return self.call_file_writer(cr, uid, ids, context=context) When the view is rendered, it shows only the two fields without it's object.

Ludo - 21South

I think it is best to create a new question for this. Post the code and we will see whoever can pick it up best.

Anirudh Lou
Autor

I have edited my post question sir.

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

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

Registrarse
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