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

PDF filename is always 'account.report_invoice' in ODOO 8

Suscribirse

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

Se marcó esta pregunta
pdffilenamenameodooV8odoo8.0
10 Respuestas
9880 Vistas
Avatar
Juan Muñoz

Hi all, 

I'm trying to change code from /addons/web/controllers/main.py

(line: file_name = '%s.%s' % (file_name, report_struct['format'])

and also trying to edit code from /addons/account/account_report.xml

(<report> tags, lines: name="Invoice" file="account.report_invoice")

BUT nothing. The generated pdf name is always the same.

I install the module 'report_custom_filename' and in the invoice reports i set 'Download filename' to (object.number)+'.pdf' just to prove.

BUT NOTHING!! All what i see gloogling is useless. Only solutions to old versions of OpenERP.

Please if anyone knows how to solve this, help me with Odoo8 :( 

Thanks so much in advance.

Juan.

1
Avatar
Descartar
Avatar
Temur
Mejor respuesta

try following:

do not change anything in original source code, then:

1. go to "Settings/Technical/Actions/Reports" page

2. find an action record that generates the PDF you're interested in.

3. As you find correct record, change it's "Save as Attachment Prefix" field as you like. 

UPDATE:

- above solution applies to pdf attachment that's saved in the database but does not apply for the pdf you download immediately after click on "Print" button in the invoice form. As it's noted in comments, you can download this invoice pdf with a preconfigured name from attachments.

What it concerns name of file that's immediately downloaded after click on the "Print" button in invoice form, most probably it requires customization.

- Python tip (take look of report's controller):


### fseudo import: import report as re 
### see: how-to-import-odoo-module-in-another-module


class ReportController(re.controllers.main.ReportController):

@route(['/report/download'])
def report_download(self, data, token):
response = super(ReportController, self).report_download(data,token) file_download_name = "Whatever you like" if "you have to handle this case(response != None, request type == 'qweb-pdf' etc...)": response.headers.set('Content-Disposition', 'attachment; filename=%s.pdf;' % file_download_name)
return response

this will cause downloaded file to have name: "Whatever you like.pdf"

actually it's not a complete solution, of course you'll need to somehow generate meaningful filename (the variable file_download_name in the code above), also it's possible that there is better place for this kind of intervention than report_download function...  good luck


2
Avatar
Descartar
Juan Muñoz
Autor

Hi Temur, thanks for your reply. I've already tried. I have this: ((object.partner_id)['name'])+'_'+(object.number)+'_'+((object.date_invoice).split('-')[1])+'.pdf' But this field only generates the attachment file stored in Settings/Database/Attachments. I want the first time you click 'Print', the generated PDF file has a name that I want. I know i can go to Settings/Database/Attachments and download the generated file with the correct name, but what I want is possible? Thanks Temur.

Temur

I'm afraid to disappoint you, but AFAIK that's not possible through configuration...

Juan Muñoz
Autor

And through .py files? I glooged about it but i only see solutions to OpenERP7 or v6.1. If anyone have the same issue pls report here.

Juan Muñoz
Autor

And through .py files? I glooged about it but i only see solutions to OpenERP7 or v6.1. If anyone have the same issue pls report here.

Temur

yes, through customisation it should be possible.. you tried to get worked the "report_custom_filename" module that you mention in the question?

Juan Muñoz
Autor

Yes. I installed it and changed the 'Download filename' field in Settings/ Reports/ Invoices, and nothing. Later also i go to /addons/report_custom_filename/controllers/reports.py and modified some lines. Because i read that this module only runs with old report actions (ir.actions.report.xml), so i added a condition -> elif(http.request.session.model('ir.actions.act_window')): #the other action type. But nothitng :(

Temur

updated answer with a python tip

Avatar
Slim BHIRI
Mejor respuesta

I just found an OCA module that does that for all reports.

https://github.com/OCA/reporting-engine/tree/9.0/report_custom_filename

You need to download all the project here :

https://github.com/OCA/reporting-engine

and don't forget to choose your Odoo version from repository branch.

0
Avatar
Descartar
Avatar
PY
Mejor respuesta

Here you go:

# -*- coding: utf-8 -*-

from openerp.addons.report.controllers.main import ReportController
from openerp.http import request, route

import simplejson



class Main(ReportController):

    def get_custom_filename(self, model, res_id):
        """Default behavior will be to get the name of the generated attachment.
        If no attachment is found, for watever reason, this method will generate 
        the filename based on the res_model.
        
        Feel free to override it if needed.
        """
        
        args = [('res_model', '=', model), ('res_id', '=', res_id)]
        attachment = request.env['ir.attachment'].search(args)

        if attachment.exists():
            return attachment.name

        record = request.env[res_model].browse(res_id)
        if record.exists():
            return '{}-{}'.format(record._table, record.name)

    @route()
    def report_download(self, data, token):
        """Attempt to generate proper filenames for qweb-pdf."""
        res = super(Main, self).report_download(data, token)
        
        data = simplejson.loads(data)
        url, report_type = data

        if report_type != 'qweb-pdf':
            return res

        report_name, res_id = url.split('/report/pdf/')[1].split('/')
        
        args = [('report_name', '=', report_name)]
        act_report = request.env['ir.actions.report.xml'].search(args)
        
        if not act_report.exists():
            return res

        filename = self.get_custom_filename(act_report.model, int(res_id))
        if not(filename):
            return res

        if not filename.endswith('.pdf'):
            filename = '{}.pdf'.format(filename)

        content_disposition = 'attachment; filename={}'.format(filename)
        res.headers.set('Content-Disposition', content_disposition)

        return res


Just put that in a module python file and install it.

0
Avatar
Descartar
¿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
"Save as Attachment Prefix" for printed invoices PDF names ignored ?
pdf printing reports name odooV8
Avatar
Avatar
1
mar 15
6600
Using with_context in super call turns into infinite call in odoo Resuelto
odooV8 odoo8.0
Avatar
Avatar
Avatar
2
ene 20
16236
Edit inherited field definition in odoo 8 Resuelto
odooV8 odoo8.0
Avatar
Avatar
Avatar
Avatar
Avatar
16
ago 19
11581
display field depending the value of another field in the view (odoo 8) Resuelto
odooV8 odoo8.0
Avatar
Avatar
1
ene 19
6149
Hide print in menu bar
odooV8 odoo8.0
Avatar
Avatar
5
jun 18
11674
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