Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • eLearning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Información
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y taberna
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y asistencia informática
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Browse all Industries
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Services for Partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

How to resolve the error “IndexError: list index out of range”?

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
python3odoo11
3 Respuestas
65749 Vistas
Avatar
Dhouha

I'm using Odoo 11 and I have installed openHRMS module but every time when I press on the dashboard menu it appears an error on this method:

IndexError: list index out of range

Ps: i tried to install this module on bitnami VM and it works whithout any problem but when i tried to installe it on ubuntu 18.04 it shows error

Any ideas on how to fix it?

 def join_resign_trends(self):
    cr = self._cr
    month_list = []
    join_trend = []
    resign_trend = []
    for i in range(11, -1, -1):
        last_month = datetime.now() - relativedelta(months=i)
        text = format(last_month, '%B %Y')
        month_list.append(text)
    for month in month_list:
        vals = {
            'l_month': month,
            'count': 0
        }
        join_trend.append(vals)
    for month in month_list:
        vals = {
            'l_month': month,
            'count': 0
        }
        resign_trend.append(vals)
    cr.execute('''select to_char(joining_date, 'Month YYYY') as l_month, count(id) from hr_employee 
    WHERE joining_date BETWEEN CURRENT_DATE - INTERVAL '12 months'
    AND CURRENT_DATE + interval '1 month - 1 day'
    group by l_month;''')
    join_data = cr.fetchall()
    cr.execute('''select to_char(resign_date, 'Month YYYY') as l_month, count(id) from hr_employee 
    WHERE resign_date BETWEEN CURRENT_DATE - INTERVAL '12 months'
    AND CURRENT_DATE + interval '1 month - 1 day'
    group by l_month;''')
    resign_data = cr.fetchall()

    for line in join_data:
        match = list(filter(lambda d: d['l_month'].replace(' ', '') == line[0].replace(' ', ''), join_trend))
        match[0]['count'] = line[1]
    for line in resign_data:
        match = list(filter(lambda d: d['l_month'].replace(' ', '') == line[0].replace(' ', ''), resign_trend))
        match[0]['count'] = line[1]
    for join in join_trend:
        join['l_month'] = join['l_month'].split(' ')[:1][0].strip()[:3]
    for resign in resign_trend:
        resign['l_month'] = resign['l_month'].split(' ')[:1][0].strip()[:3]
    graph_result = [{
        'name': 'Join',
        'values': join_trend
    }, {
        'name': 'Resign',
        'values': resign_trend
    }]
    return graph_result

 def get_attrition_rate(self):
    month_attrition = []
    monthly_join_resign = self.join_resign_trends()
    month_join = monthly_join_resign[0]['values']
    month_resign = monthly_join_resign[1]['values']
    sql = """
    SELECT (date_trunc('month', CURRENT_DATE))::date - interval '1' month * s.a AS month_start 
    FROM generate_series(0,11,1) AS s(a);"""
    self._cr.execute(sql)
    month_start_list = self._cr.fetchall()
    for month_date in month_start_list:
        self._cr.execute("""select count(id), to_char(date '%s', 'Month YYYY') as l_month from hr_employee 
        where resign_date> date '%s' or resign_date is null and joining_date < date '%s'
        """ % (month_date[0], month_date[0], month_date[0],))
        month_emp = self._cr.fetchone()
        # month_emp = (month_emp[0], month_emp[1].split(' ')[:1][0].strip()[:3])
        match_join = list(filter(lambda d: d['l_month'] == month_emp[1].split(' ')[:1][0].strip()[:3], month_join))[0]['count']
        match_resign = list(filter(lambda d: d['l_month'] == month_emp[1].split(' ')[:1][0].strip()[:3], month_resign))[0]['count']
        month_avg = (month_emp[0]+match_join-match_resign+month_emp[0])/2
        attrition_rate = (match_resign/month_avg)*100 if month_avg != 0 else 0
        vals = {
            # 'month': month_emp[1].split(' ')[:1][0].strip()[:3] + ' ' + month_emp[1].split(' ')[-1:][0],
            'month': month_emp[1].split(' ')[:1][0].strip()[:3],
            'attrition_rate': round(float(attrition_rate), 2)
        }
        month_attrition.append(vals)
    return month_attrition

traceback

   Traceback (most recent call last):
   File "/opt/openhrms/odoo/http.py", line 651, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
  File "/opt/openhrms/odoo/http.py", line 310, in _handle_exception
raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/opt/openhrms/odoo/tools/pycompat.py", line 87, in reraise
raise value
  File "/opt/openhrms/odoo/http.py", line 693, in dispatch
result = self._call_function(**self.params)
  File "/opt/openhrms/odoo/http.py", line 342, in _call_function
return checked_call(self.db, *args, **kwargs)
  File "/opt/openhrms/odoo/service/model.py", line 97, in wrapper
return f(dbname, *args, **kwargs)
  File "/opt/openhrms/odoo/http.py", line 335, in checked_call
result = self.endpoint(*a, **kw)
  File "/opt/openhrms/odoo/http.py", line 937, in __call__
return self.method(*args, **kw)
  File "/opt/openhrms/odoo/http.py", line 515, in response_wrap
response = f(*args, **kw)
 File "/opt/openhrms/addons/web/controllers/main.py", line 934, in call_kw
return self._call_kw(model, method, args, kwargs)
 File "/opt/openhrms/addons/web/controllers/main.py", line 926, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
 File "/opt/openhrms/odoo/api.py", line 687, in call_kw
return call_kw_model(method, model, args, kwargs)
 File "/opt/openhrms/odoo/api.py", line 672, in call_kw_model
result = method(recs, *args, **kwargs)
 File "/opt/openhrms/openhrms/hrms_dashboard/models/hrms_dashboard.py", line 384, in get_attrition_rate
monthly_join_resign = self.join_resign_trends()
 File "/opt/openhrms/openhrms/hrms_dashboard/models/hrms_dashboard.py", line 364, in join_resign_trends
match[0]['count'] = line[1]
IndexError: list index out of range
0
Avatar
Descartar
Yenthe Van Ginneken (Mainframe Monkey)

line[1] doesn't exist as line[] is empty (or only has [0]) which gives this error.

Dhouha
Autor

Thanks for your answer i tried to modify line[1] --> line[0] but it shows the same error

Avatar
Bhaviraj Brahmkshatriya
Mejor respuesta

Hello Dhouda,

Put some print statements. May be it will help. i thing no data is coming into sql query, so it is blank list.

and it is blank list if you do list[0] even though it gives same error. So verify your code.

0
Avatar
Descartar
¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
How to set a filter as default filter in odoo Resuelto
python3 odoo11
Avatar
Avatar
Avatar
2
feb 24
16671
How to set default stage to when recruitement record is created Resuelto
python3 odoo11
Avatar
Avatar
1
dic 22
5787
How to change the value of a field which depends on other fields automatically ? Resuelto
python3 odoo11
Avatar
Avatar
Avatar
2
dic 22
15615
how to modify fields of hr.attendance via a modification request automatically Resuelto
python3 odoo11
Avatar
Avatar
Avatar
2
jun 22
7763
how to update field of attendance via an attendance request modification
python3 odoo11
Avatar
Avatar
Avatar
2
jun 22
5730
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

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