Odoo Help

Welcome!

This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.

0

Computed value for binary fields

By
Aidas Bendoraitis
on 11/7/16, 4:22 PM 148 views

I am trying to create a model for product images in Odoo 10. A product image can have one original uploaded image and two computed versions: medium and small. This is the code I wrote:

# -*- coding: utf-8 -*-
from odoo import models, fields, api, tools

class ProductImage(models.Model):
    _name = 'product_images.product_image'
  _description = 'Product image'

    name = fields.Char(string="Alternative text")
  product_id = fields.Many2one('product.product', string='Product', ondelete='set null', index=True)
  original_image = fields.Binary(string='Original image')
    medium_image = fields.Binary(string='Medium image', compute='_resize_image', store=True)
  small_image = fields.Binary(string='Small image', compute='_resize_image', store=True)

    @api.depends('original_image')
  def _resize_image(self):
        for record in self.with_context(bin_size=False):
            data = tools.image_get_resized_images(record.original_image)
 record.medium_image = data['image_medium']
  record.small_image = data['image_small']


When I change the original_image in the form view or in the Odoo shell, _resize_image() is called, but medium_image and small_image values are not saved. What do I miss?


after save the form don't you see the image shrinks??

Axel Mendoza
on 11/8/16, 2:04 AM

Unfortunately not. I see empty values for the medium_image and small_image.

Aidas Bendoraitis
on 11/8/16, 8:15 AM

I also tried @api.onchange for the binary image, but that didn't work either.

Aidas Bendoraitis
on 11/8/16, 10:14 AM
0
Aidas Bendoraitis
On 11/8/16, 1:13 PM

After lots of trial and error, I found out that I can't set empty context for the record to be modified, because then the assignment statement doesn't save the record to the database. So I ended up with this code:

    @api.depends('original_image')    
def _resize_image(self):
        original_image = self.with_context({}).original_image
if original_image:
            data = tools.image_get_resized_images(original_image)
self.medium_image = data['image_medium']
self.small_image = data['image_small']
else:
            self.medium_image = ""
self.small_image = ""

Your Answer

Please try to give a substantial answer. If you wanted to comment on the question or answer, just use the commenting tool. Please remember that you can always revise your answers - no need to answer the same question twice. Also, please don't forget to vote - it really helps to select the best questions and answers!

About This Community

This community is for professionals and enthusiasts of our products and services. Read Guidelines

Question tools

1 follower(s)

Stats

Asked: 11/7/16, 4:22 PM
Seen: 148 times
Last updated: 11/8/16, 1:13 PM