Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

AttributeError: 'NoneType' object has no attribute 'values' (Odoo 13)

Subscriure's

Get notified when there's activity on this post

This question has been flagged
onchangeattributeerrorproject.task
2 Respostes
69909 Vistes
Avatar
Nathan Cobb

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'
0
Avatar
Descartar
Ibrahim Boudmir

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

make sure you have repartition before retrieving its values.

Nathan Cobb
Autor

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.

Avatar
Gracious Joseph
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.

0
Avatar
Descartar
Avatar
markaldo
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


0
Avatar
Descartar
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Related Posts Respostes Vistes Activitat
Calling Activity_feedback in an @api.onchange() causes error. Solved
onchange project.task scheduleactivty
Avatar
1
d’ag. 22
3657
How to restrict that only creators and assignees with permissions can see their own tasks in project?
project.task
Avatar
Avatar
Avatar
2
de maig 25
3528
Make is_closed field for a task editable
project.task
Avatar
Avatar
Avatar
2
de jul. 24
2565
trying to auto correct a wrong users value
onchange
Avatar
Avatar
1
d’oct. 23
2807
"Wrong value for %s: %r" % (self, value) Solved
onchange
Avatar
Avatar
2
d’oct. 23
3033
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now