Skip to content

Instantly share code, notes, and snippets.

@CakJuice
Created August 18, 2018 02:50
Show Gist options
  • Save CakJuice/6fbccf4af48fff5bb5a5f0e9283295df to your computer and use it in GitHub Desktop.
Save CakJuice/6fbccf4af48fff5bb5a5f0e9283295df to your computer and use it in GitHub Desktop.
Generate attachment on Odoo 11
import base64
from odoo import models, fields, api
class SomeModel(models.Model):
_name = 'some.model'
field1 = fields.Char(string="Field 1")
field2 = fields.Boolean(string="Field 2")
@api.multi
def action_generate_attachment(self):
""" this method called from button action in view xml """
# generate pdf from report, use report's id as reference
REPORT_ID = 'some_report_id'
pdf = self.env.ref(REPORT_ID).render_qweb_pdf(self.ids)
# pdf result is a list
b64_pdf = base64.b64encode(pdf[0])
# save pdf as attachment
ATTACHMENT_NAME = "My Attachment Name"
return self.env['ir.attachment'].create({
'name': ATTACHMENT_NAME,
'type': 'binary',
'datas': b64_pdf,
'datas_fname': ATTACHMENT_NAME + '.pdf',
'store_fname': ATTACHMENT_NAME,
'res_model': self._name,
'res_id': self.id,
'mimetype': 'application/x-pdf'
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment