Newer
Older
from odoo import _, api, exceptions, fields, models
class DocumentAttachmentType(models.Model):
"""Kind of document that can be attached."""
name = fields.Char(string="Description", size=256, required=True)
model = fields.Char(string="Model", size=128, required=True)
class DocumentAttachment(models.Model):
"""A document that can be attached.
Inherit[s] from ir.attachment to store documents as attachments.
"""
comodel_name="document_attachment.type", string="Type", required=True
comodel_name="ir.attachment",
string="File",
ondelete="cascade",
required=True,
delegate=True,
)
@api.model
def create(self, vals):
"""- Fill the "name" from the original filename.
- Associate the new attachment with the current object.
"""
# When wrapping an existing attachment, no need to pre-fill data.
if vals.get("file_id"):
return super(DocumentAttachment, self).create(vals)
raise exceptions.Warning(
_("You must send the 'res_model' through the m2m context")
)
raise exceptions.Warning(
_("You must send the 'res_id' through the m2m context")
)
vals["res_model"] = context["res_model"]
vals["res_id"] = context["res_id"]
return super(DocumentAttachment, self).create(vals)
@api.multi
def write(self, vals):
"""Fill the "name" from the original filename."""
if "datas_fname" in vals:
vals["name"] = vals["datas_fname"]
return super(DocumentAttachment, self).write(vals)
@api.multi
def unlink(self):
"""Delete the attachment associated with records being deleted."""
attachment_ids = [doc.file_id.id for doc in self]
ret = super(DocumentAttachment, self).unlink()
attachments = self.env["ir.attachment"].browse(attachment_ids)
@api.multi
def get_metadata(self):
"""Helper function returning the document attachment metadata
Can be overridden to add some specifics metadata
"""
self.ensure_one()
return {
"size": self.file_size,
"type": self.mimetype,
"filename": self._context.get("datas_fname", self.datas_fname),
"hash": ["sha1:%s" % self.checksum],
"encoding": "",
"customtype": self.type_id.name,
}