Search code examples
python-3.xodooodoo-12

Odoo 12 - Generate and download CSV file


I have added a menu item in Reporting Tab in Manufacturing module. I have already written python code to create CSV file. But unable to figure out how to make it downloadable when I click the menu item in manufacturing module. Here is the menu item code:

 <record model="ir.actions.server" id="raw_material_planning">
    <field name="name">Raw Material Planning</field>
    <field name="type">ir.actions.server</field>
    <field name="res_model">gear.manufacturing</field>
    <field name="model_id">342</field>
    <field name="state">code</field>
    <field name="code">
        action = model.raw_material_planning()
    </field>
  </record>

  <menuitem name="Raw Material Planning" parent="mrp.menu_mrp_reporting" id="menu_raw_material_planning"
      action="raw_material_planning"/>

Also, it should directly download and not go to any window.

UPDATE

saved dictionary to CSV file

files = base64.b64encode(open('test.csv','rb').read())

attachment = self.env['ir.attachment'].create({
            'name': 'test.csv',
            'datas': files,
            'datas_fname': 'test.csv'
        })

return {
            'type': 'ir.actions.act_url',
            'url': '/web/content/%s?download=true' % (attachment.id),
            # 'target': 'new',
            'nodestroy': False,
        }

Kindly assist me


Solution

  • Here is all controllers are available for download contents or files.

    You need to return any of controller with your file content it will automatically download.

    [
      '/web/content',
      '/web/content/<string:xmlid>',
      '/web/content/<string:xmlid>/<string:filename>',
      '/web/content/<int:id>',
      '/web/content/<int:id>/<string:filename>',
      '/web/content/<int:id>-<string:unique>',
      '/web/content/<int:id>-<string:unique>/<string:filename>',
      '/web/content/<string:model>/<int:id>/<string:field>',
      '/web/content/<string:model>/<int:id>/<string:field>/<string:filename>'
    ]
    

    For download any file you need to create one attachment record for ir.attachment.

    Then just add below code in your function for return file to url.

    attachment = self.env['ir.attachment'].search([('name', '=', 'import_product_sample')])
    return {
        'type': 'ir.actions.act_url',
        'url': '/web/content/%s?download=true' % (attachment.id),
        'target': 'new',
        'nodestroy': False,
    }
    

    It will automatically download your file in browser.