Skip to Content
Menu
This question has been flagged
2 Replies
66925 Views

I am creating an addon template functionality to the project module. I would like users to be able to select/change the template from the project form view, but in my onchange function for taskset_template_id it is throwing up an error when I try to delete existing tasks that were created from a previously applied template (only one template at a time should be used). It seems to be a dependency or context issue with the rating mixin, but I've tried adding the 'rating' module to the __manifest__.py file and tasks still aren't successfully unlinked. How can I unlink tasks without running into this rating issue?

The code:

@api.onchange('taskset_template_id')
def onchange_taskset_template_id(self):
if not self.project_deadline:
raise ValidationError('In order to apply a taskset template you must first select a project deadline.')
project = self.env['project.project'].browse(self._origin.id)
tasks = self.env['project.task']

# Check for template tasks delete to avoid task duplication
find_template_tasks = self.env['project.task'].search([('project_id', '=', project.id), ('from_template', '=', True)])
if find_template_tasks:
for task in tasks.browse(find_template_tasks.ids):
super(Task, task).unlink()

if not self.taskset_template_id:
raise ValidationError(
'You have already applied a taskset template to this project. Before removing the template selection, please delete all tasks associated with the current template.'
)

task_ids = self.env['taskset.template.line'].search([('taskset_template_id', '=', self.taskset_template_id.id)]).ids

for task in self.env['taskset.template.line'].browse(task_ids):
data = self._map_template_tasks_default_values(task)

# Calculate deadline
days_from_deadline = task.day_counter
deadline = self._calculate_deadline(self.project_deadline, days_from_deadline, project)
data.update({'project_id': project.id,
'date_deadline': deadline,
'date_assign': fields.Datetime.now(),
'partner_id': self.partner_id.id,
'from_template': True})

new_task = super(Task, tasks).create(data)
tasks += new_task

project.write({'tasks': [(tasks.ids)]})

The error:

Traceback (most recent call last):
  File "/Users/nathancobb/odoo/odoo/odoo/api.py", line 753, in get
    value = self._data[field][record._ids[0]]
KeyError: <NewId origin=4>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/nathancobb/odoo/odoo/odoo/fields.py", line 978, in __get__
    value = env.cache.get(record, self)
  File "/Users/nathancobb/odoo/odoo/odoo/api.py", line 759, in get
    raise CacheMiss(record, field)
odoo.exceptions.CacheMiss: ('project.project(<NewId origin=4>,).rating_percentage_satisfaction', None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/nathancobb/odoo/odoo/odoo/http.py", line 619, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/Users/nathancobb/odoo/odoo/odoo/http.py", line 309, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/Users/nathancobb/odoo/odoo/odoo/tools/pycompat.py", line 14, in reraise
    raise value
  File "/Users/nathancobb/odoo/odoo/odoo/http.py", line 664, in dispatch
    result = self._call_function(**self.params)
  File "/Users/nathancobb/odoo/odoo/odoo/http.py", line 345, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/Users/nathancobb/odoo/odoo/odoo/service/model.py", line 93, in wrapper
    return f(dbname, *args, **kwargs)
  File "/Users/nathancobb/odoo/odoo/odoo/http.py", line 338, in checked_call
    result = self.endpoint(*a, **kw)
  File "/Users/nathancobb/odoo/odoo/odoo/http.py", line 909, in __call__
    return self.method(*args, **kw)
  File "/Users/nathancobb/odoo/odoo/odoo/http.py", line 510, in response_wrap
    response = f(*args, **kw)
  File "/Users/nathancobb/odoo/odoo/addons/web/controllers/main.py", line 1319, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/Users/nathancobb/odoo/odoo/addons/web/controllers/main.py", line 1311, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/Users/nathancobb/odoo/odoo/odoo/api.py", line 395, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)
  File "/Users/nathancobb/odoo/odoo/odoo/api.py", line 382, in _call_kw_multi
    result = method(recs, *args, **kwargs)
  File "/Users/nathancobb/odoo/odoo/odoo/models.py", line 6050, in onchange
    todo = [
  File "/Users/nathancobb/odoo/odoo/odoo/models.py", line 6053, in <listcomp>
    if name not in done and snapshot0.has_changed(name)
  File "/Users/nathancobb/odoo/odoo/odoo/models.py", line 5920, in has_changed
    return self[name] != record[name]
  File "/Users/nathancobb/odoo/odoo/odoo/models.py", line 5579, in __getitem__
    return self._fields[key].__get__(self, type(self))
  File "/Users/nathancobb/odoo/odoo/odoo/fields.py", line 1002, in __get__
    self.compute_value(recs)
  File "/Users/nathancobb/odoo/odoo/odoo/fields.py", line 1087, in compute_value
    records._compute_field_value(self)
  File "/Users/nathancobb/odoo/odoo/odoo/models.py", line 3895, in _compute_field_value
    getattr(self, field.compute)()
  File "/Users/nathancobb/odoo/odoo/addons/rating/models/rating_mixin.py", line 42, in _compute_rating_percentage_satisfaction
    record.rating_percentage_satisfaction = repartition['great'] * 100 / sum(repartition.values()) if sum(repartition.values()) else -1
AttributeError: 'NoneType' object has no attribute 'values'
Avatar
Discard

you're trying ot get values of an empty repartition.

make sure you have repartition before retrieving its values.

Author

Right, but I don't understand why repartition is being referenced in the first place. I can't find a function call for _compute_rating_percentage_satisfaction (the only place where repartition is used) anywhere in the project.project or project.task models.

Best Answer

The error AttributeError: 'NoneType' object has no attribute 'values' in the given context indicates that some variable in the method _compute_rating_percentage_satisfaction (specifically repartition) is None, and the code is attempting to call .values() on it. This issue is related to the rating mixin being included in your model (project.project or project.task) but not properly initialized or used.

Here’s how you can resolve this issue step-by-step:

1. Understand the Root Cause

  • Where repartition Comes From: The _compute_rating_percentage_satisfaction method expects repartition to contain a dictionary of ratings, but it's None. This could happen because:
    • The rating module is not fully initialized for the model.
    • The context or data required to compute ratings (e.g., existing rating records) is missing.
  • Why It’s Triggered: The rating_percentage_satisfaction field, which is a computed field, is being triggered by your onchange function when you modify taskset_template_id. This occurs because computed fields are recalculated whenever their dependencies or context are accessed, even indirectly.

2. Quick Fix: Avoid the Computed Field Execution

To prevent the computed field from being triggered during your onchange_taskset_template_id method:

  1. Use with_context to Bypass Rating Fields: Add a custom context key and skip the computation of the rating field temporarily:
    @api.onchange('taskset_template_id')
    def onchange_taskset_template_id(self):
        if not self.project_deadline:
            raise ValidationError('In order to apply a taskset template you must first select a project deadline.')
        
        project = self.with_context(skip_rating=True).env['project.project'].browse(self._origin.id)
        tasks = self.env['project.task']
    
        # Check for template tasks delete to avoid task duplication
        find_template_tasks = self.env['project.task'].search([
            ('project_id', '=', project.id),
            ('from_template', '=', True)
        ])
        if find_template_tasks:
            for task in tasks.browse(find_template_tasks.ids):
                super(Task, task).unlink()
    
  2. Modify the rating.mixin Compute Method: Update _compute_rating_percentage_satisfaction in the rating mixin to skip computation when the context has the skip_rating key:
    def _compute_rating_percentage_satisfaction(self):
        for record in self:
            if self.env.context.get('skip_rating'):
                record.rating_percentage_satisfaction = -1
                continue
            repartition = record._get_rating_repartition()
            record.rating_percentage_satisfaction = (
                repartition['great'] * 100 / sum(repartition.values())
                if repartition and sum(repartition.values()) else -1
            )
    

3. Verify repartition Initialization

If the _compute_rating_percentage_satisfaction method still fails after the above steps, ensure the repartition dictionary is correctly initialized in _get_rating_repartition.

Check _get_rating_repartition Implementation:

  • Ensure this method is returning a valid dictionary, not None. You can override it if necessary:
    def _get_rating_repartition(self):
        if not self.rating_ids:
            return {'great': 0, 'good': 0, 'bad': 0}
        # Custom logic to compute repartition
        return super()._get_rating_repartition()
    

4. Clean Up Unnecessary Dependencies

If you’re not using the rating functionality:

  • Remove the rating.mixin dependency entirely from your model:
    class Project(models.Model):
        _inherit = 'project.project'
    
        # Remove unnecessary fields or mixins
        rating_percentage_satisfaction = fields.Float(compute=False, store=False)
    
  • If the rating.mixin is critical for other functionalities, keep it but ensure its fields are not triggered unnecessarily.

5. Debugging the Issue

Use logging to identify exactly when repartition becomes None:

import logging
_logger = logging.getLogger(__name__)

def _compute_rating_percentage_satisfaction(self):
    for record in self:
        try:
            repartition = record._get_rating_repartition()
            _logger.info(f"Repartition: {repartition}")
            record.rating_percentage_satisfaction = (
                repartition['great'] * 100 / sum(repartition.values())
                if sum(repartition.values()) else -1
            )
        except Exception as e:
            _logger.error(f"Error computing satisfaction: {e}")
            record.rating_percentage_satisfaction = -1

Check the logs for errors and adjust the computation logic accordingly.

6. Best Practices for Onchange Functions

  1. Avoid Complex Logic in Onchange: If possible, move the task deletion and creation logic to a button action or a method triggered during the record save.
  2. Add Validation to Prevent Recursive Errors: Use context keys to prevent fields like rating_percentage_satisfaction from being recomputed unnecessarily.

Summary

  • Temporarily bypass the rating_percentage_satisfaction computation during your onchange function by using with_context.
  • Ensure the _get_rating_repartition method always returns a dictionary, not None.
  • Clean up the rating.mixin dependency if it’s not needed.

If you still encounter issues, let me know, and I can provide further assistance or help debug specific parts of the implementation.

Avatar
Discard
Best Answer

AttributeError means that there was an Error that had to do with an Attribute request. In general, when you write x.y, y is the purported attribute of x. NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None. That usually means that an assignment or function call up failed or returned an unexpected result.

mylist = mylist.sort()

The sort() method of a list sorts the list in-place, that is, mylist is modified. But the actual return value of the method is None and not the list sorted. So you've just assigned None to mylist. If you next try to do, say, mylist.append(1) Python will give you this error.

http://net-informations.com/python/basics/none.htm


Avatar
Discard
Related Posts Replies Views Activity
1
Aug 22
1941
2
Jul 24
587
1
Oct 23
363
2
Oct 23
675
2
Aug 23
1963