Skip ke Konten
Odoo Menu
  • Login
  • Uji coba gratis
  • Aplikasi
    Keuangan
    • Akuntansi
    • Faktur
    • Pengeluaran
    • Spreadsheet (BI)
    • Dokumen
    • Tanda Tangan
    Sales
    • CRM
    • Sales
    • POS Toko
    • POS Restoran
    • Langganan
    • Rental
    Website
    • Website Builder
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Rantai Pasokan
    • Inventaris
    • Manufaktur
    • PLM
    • Purchase
    • Maintenance
    • Kualitas
    Sumber Daya Manusia
    • Karyawan
    • Rekrutmen
    • Cuti
    • Appraisal
    • Referensi
    • Armada
    Marketing
    • Social Marketing
    • Email Marketing
    • SMS Marketing
    • Acara
    • Otomatisasi Marketing
    • Survei
    Layanan
    • Project
    • Timesheet
    • Layanan Lapangan
    • Meja Bantuan
    • Planning
    • Appointment
    Produktivitas
    • Discuss
    • Approval
    • IoT
    • VoIP
    • Pengetahuan
    • WhatsApp
    Aplikasi pihak ketiga Odoo Studio Platform Odoo Cloud
  • Industri-Industri
    Retail
    • Toko Buku
    • Toko Baju
    • Toko Furnitur
    • Toko Kelontong
    • Toko Hardware
    • Toko Mainan
    Makanan & Hospitality
    • Bar dan Pub
    • Restoran
    • Fast Food
    • Rumah Tamu
    • Distributor Minuman
    • Hotel
    Real Estate
    • Agensi Real Estate
    • Firma Arsitektur
    • Konstruksi
    • Estate Management
    • Perkebunan
    • Asosiasi Pemilik Properti
    Konsultansi
    • Firma Akuntansi
    • Mitra Odoo
    • Agensi Marketing
    • Firma huku
    • Talent Acquisition
    • Audit & Sertifikasi
    Manufaktur
    • Tekstil
    • Logam
    • Perabotan
    • Makanan
    • Brewery
    • Corporate Gift
    Kesehatan & Fitness
    • Sports Club
    • Toko Kacamata
    • Fitness Center
    • Wellness Practitioners
    • Farmasi
    • Salon Rambut
    Perdagangan
    • Handyman
    • IT Hardware & Support
    • Sistem-Sistem Energi Surya
    • Pembuat Sepatu
    • Cleaning Service
    • Layanan HVAC
    Lainnya
    • Organisasi Nirlaba
    • Agen Lingkungan
    • Rental Billboard
    • Fotografi
    • Penyewaan Sepeda
    • Reseller Software
    Browse semua Industri
  • Komunitas
    Belajar
    • Tutorial-tutorial
    • Dokumentasi
    • Sertifikasi
    • Pelatihan
    • Blog
    • Podcast
    Empower Education
    • Program Edukasi
    • Game Bisnis 'Scale Up!'
    • Kunjungi Odoo
    Dapatkan Softwarenya
    • Download
    • Bandingkan Edisi
    • Daftar Rilis
    Kolaborasi
    • Github
    • Forum
    • Acara
    • Terjemahan
    • Menjadi Partner
    • Layanan untuk Partner
    • Daftarkan perusahaan Akuntansi Anda.
    Dapatkan Layanan
    • Temukan Mitra
    • Temukan Akuntan
    • Temui penasihat
    • Layanan Implementasi
    • Referensi Pelanggan
    • Bantuan
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Dapatkan demo
  • Harga
  • Bantuan

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

  • CRM
  • e-Commerce
  • Akuntansi
  • Inventaris
  • PoS
  • Project
  • MRP
All apps
Anda harus terdaftar untuk dapat berinteraksi di komunitas.
Semua Post Orang Lencana-Lencana
Label (Lihat semua)
odoo accounting v14 pos v15
Mengenai forum ini
Anda harus terdaftar untuk dapat berinteraksi di komunitas.
Semua Post Orang Lencana-Lencana
Label (Lihat semua)
odoo accounting v14 pos v15
Mengenai forum ini
Help

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

Langganan

Dapatkan notifikasi saat terdapat aktivitas pada post ini

Pertanyaan ini telah diberikan tanda
onchangeattributeerrorproject.task
2 Replies
70104 Tampilan
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
Buang
Ibrahim Boudmir

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

make sure you have repartition before retrieving its values.

Nathan Cobb
Penulis

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
Jawaban Terbai

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
Buang
Avatar
markaldo
Jawaban Terbai

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
Buang
Menikmati diskusi? Jangan hanya membaca, ikuti!

Buat akun sekarang untuk menikmati fitur eksklufi dan agar terlibat dengan komunitas kami!

Daftar
Post Terkait Replies Tampilan Aktivitas
Calling Activity_feedback in an @api.onchange() causes error. Diselesaikan
onchange project.task scheduleactivty
Avatar
1
Agu 22
3786
How to restrict that only creators and assignees with permissions can see their own tasks in project?
project.task
Avatar
Avatar
Avatar
2
Mei 25
3627
Make is_closed field for a task editable
project.task
Avatar
Avatar
Avatar
2
Jul 24
2661
trying to auto correct a wrong users value
onchange
Avatar
Avatar
1
Okt 23
2931
"Wrong value for %s: %r" % (self, value) Diselesaikan
onchange
Avatar
Avatar
2
Okt 23
3182
Komunitas
  • Tutorial-tutorial
  • Dokumentasi
  • Forum
Open Source
  • Download
  • Github
  • Runbot
  • Terjemahan
Layanan
  • Odoo.sh Hosting
  • Bantuan
  • Peningkatan
  • Custom Development
  • Pendidikan
  • Temukan Akuntan
  • Temukan Mitra
  • Menjadi Partner
Tentang Kami
  • Perusahaan kami
  • Aset Merek
  • Hubungi kami
  • Tugas
  • Acara
  • Podcast
  • Blog
  • Pelanggan
  • Hukum • Privasi
  • Keamanan
الْعَرَبيّة 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 adalah rangkaian aplikasi bisnis open source yang mencakup semua kebutuhan perusahaan Anda: CRM, eCommerce, akuntansi, inventaris, point of sale, manajemen project, dan seterusnya.

Mudah digunakan dan terintegrasi penuh pada saat yang sama adalah value proposition unik Odoo.

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