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
    • e-learning
    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
    • Conocimientos
    • 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 pub
    • 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
    • Cervecería
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y soporte técnico
    • 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
    Explorar todos los sectores
  • 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
    • Servicios para 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 create .DAT file?

Suscribirse

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

Se marcó esta pregunta
1 Responder
13002 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.

Inscribirse
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