Skip to Content
Odoo Menu
  • Prihlásiť sa
  • Vyskúšajte zadarmo
  • Aplikácie
    Financie
    • Účtovníctvo
    • Fakturácia
    • Výdavky
    • Tabuľka (BI)
    • Dokumenty
    • Podpis
    Predaj
    • CRM
    • Predaj
    • POS Shop
    • POS Restaurant
    • Manažment odberu
    • Požičovňa
    Webstránky
    • Tvorca webstránok
    • eShop
    • Blog
    • Fórum
    • Živý chat
    • eLearning
    Supply Chain
    • Sklad
    • Výroba
    • Správa životného cyklu produktu
    • Nákup
    • Údržba
    • Manažment kvality
    Ľudské zdroje
    • Zamestnanci
    • Nábor zamestnancov
    • Voľné dni
    • Hodnotenia
    • Odporúčania
    • Vozový park
    Marketing
    • Marketing sociálnych sietí
    • Email marketing
    • SMS marketing
    • Eventy
    • Marketingová automatizácia
    • Prieskumy
    Služby
    • Projektové riadenie
    • Pracovné výkazy
    • Práca v teréne
    • Helpdesk
    • Plánovanie
    • Schôdzky
    Produktivita
    • Tímová komunikácia
    • Schvalovania
    • IoT
    • VoIP
    • Znalosti
    • WhatsApp
    Third party apps Odoo Studio Odoo Cloud Platform
  • Priemyselné odvetvia
    Retail
    • Book Store
    • Clothing Store
    • Furniture Store
    • Grocery Store
    • Hardware Store
    • Toy Store
    Food & Hospitality
    • Bar and Pub
    • Reštaurácia
    • Fast Food
    • Guest House
    • Beverage distributor
    • Hotel
    Reality
    • Real Estate Agency
    • Architecture Firm
    • Konštrukcia
    • Estate Managament
    • Gardening
    • Property Owner Association
    Poradenstvo
    • Accounting Firm
    • Odoo Partner
    • Marketing Agency
    • Law firm
    • Talent Acquisition
    • Audit & Certification
    Výroba
    • Textile
    • Metal
    • Furnitures
    • Jedlo
    • Brewery
    • Corporate Gifts
    Health & Fitness
    • Sports Club
    • Eyewear Store
    • Fitness Center
    • Wellness Practitioners
    • Pharmacy
    • Hair Salon
    Trades
    • Handyman
    • IT Hardware and Support
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Iní
    • Nonprofit Organization
    • Environmental Agency
    • Billboard Rental
    • Photography
    • Bike Leasing
    • Software Reseller
    Browse all Industries
  • Komunita
    Vzdelávanie
    • Tutoriály
    • Dokumentácia
    • Certifikácie
    • Školenie
    • Blog
    • Podcast
    Empower Education
    • Vzdelávací program
    • Scale Up! Business Game
    • Visit Odoo
    Softvér
    • Stiahnuť
    • Porovnanie Community a Enterprise vierzie
    • Releases
    Spolupráca
    • Github
    • Fórum
    • Eventy
    • Preklady
    • Staň sa partnerom
    • Services for Partners
    • Register your Accounting Firm
    Služby
    • Nájdite partnera
    • Nájdite účtovníka
    • Meet an advisor
    • Implementation Services
    • Zákaznícke referencie
    • Podpora
    • Upgrades
    ​Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Získajte demo
  • Cenník
  • Pomoc

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

  • CRM
  • e-Commerce
  • Účtovníctvo
  • Sklady
  • PoS
  • Projektové riadenie
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Tagy (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Tagy (View all)
odoo accounting v14 pos v15
About this forum
Pomoc

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

Odoberať

Get notified when there's activity on this post

This question has been flagged
onchangeattributeerrorproject.task
2 Replies
70030 Zobrazenia
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
Zrušiť
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
Zrušiť
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
Zrušiť
Enjoying the discussion? Don't just read, join in!

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

Registrácia
Related Posts Replies Zobrazenia Aktivita
Calling Activity_feedback in an @api.onchange() causes error. Solved
onchange project.task scheduleactivty
Avatar
1
aug 22
3730
How to restrict that only creators and assignees with permissions can see their own tasks in project?
project.task
Avatar
Avatar
Avatar
2
máj 25
3603
Make is_closed field for a task editable
project.task
Avatar
Avatar
Avatar
2
júl 24
2651
trying to auto correct a wrong users value
onchange
Avatar
Avatar
1
okt 23
2921
"Wrong value for %s: %r" % (self, value) Solved
onchange
Avatar
Avatar
2
okt 23
3154
Komunita
  • Tutoriály
  • Dokumentácia
  • Fórum
Open Source
  • Stiahnuť
  • Github
  • Runbot
  • Preklady
Služby
  • Odoo.sh hosting
  • Podpora
  • Vyššia verzia
  • Custom Developments
  • Vzdelávanie
  • Nájdite účtovníka
  • Nájdite partnera
  • Staň sa partnerom
O nás
  • Naša spoločnosť
  • Majetok značky
  • Kontaktujte nás
  • Pracovné ponuky
  • Eventy
  • Podcast
  • Blog
  • Zákazníci
  • Právne dokumenty • Súkromie
  • Bezpečnosť
الْعَرَبيّة 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 je sada podnikových aplikácií s otvoreným zdrojovým kódom, ktoré pokrývajú všetky potreby vašej spoločnosti: CRM, e-shop, účtovníctvo, skladové hospodárstvo, miesto predaja, projektový manažment atď.

Odoo prináša vysokú pridanú hodnotu v jednoduchom použití a súčasne plne integrovanými biznis aplikáciami.

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