Search code examples
singletonodooattachment

Odoo Singleton error when putting more then one attachment


Hello i am trying to send multiple attachment in one email, here is the code that i used:

def action_send_card(self):
template_id = self.env.ref('library.agreement_email_template').id
data_id = self.env['ir.attachment'].browse(self.agreement_file.id)
        template = self.env['mail.template'].browse(template_id)
        for pdf in data_id:
            template.attachment_ids = [(3, pdf.id)]
            template.attachment_ids = [(6, 0, [pdf.id])]
        template.send_mail(self.id, force_send=True)
        return True

i tried it with one file its work great but when i try two files or more it gives me the same error.

ValueError: Expected singleton: ir.attachment(260, 257)

The agreement_file is declared like this:

agreement_file = fields.Many2many(
        'ir.attachment',
        'class_ir_attachments_rel',
        'class_id',
        'attachment_id',
        string="Agreement files",
        required=False)

Solution

  • I tried some of the solutions in here but it still didnt work. I changed something in the code and somehow i found the solution. Here it is

        def action_send_card(self):
            template_id = self.env.ref('library.agreement_email_template').id
            data_id = self.env['ir.attachment'].browse(self.agreement_file.ids)
            template = self.env['mail.template'].browse(template_id)
            for existing_pdf in template.attachment_ids:
                template.write({"attachment_ids": [(3, existing_pdf.id)]})
            for pdf in data_id:
                for new_pdf in pdf:
                    template.write({"attachment_ids": [(4, new_pdf.id)]})
            template.send_mail(self.id, force_send=True)