Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita 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
  • Proyectos
  • 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

IndexError: list index out of range need a help

Suscribirse

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

Se marcó esta pregunta
2 Respuestas
16754 Vistas
Avatar
ABU K

Here   I attached entire .py code and .xml file one of button event returns  IndexError: list index out of range  error need a help 

function name is

  def  check_eligibility(

.py file-------------------


from osv import osv,fields
import time
from datetime import datetime
from datetime import timedelta

class hr_employee(osv.osv):

     _name='hr.employee'
     _inherit=['hr.employee','mail.thread']

     _columns={
              'date_of_join' :fields.date('Date of Join',required=True),
              'current_date':fields.date('Applied date',require=True),
              'eligible_details':fields.char('Eligibility Details'),
              'visaexpiry_date':fields.date('Visa Expiry Date'),
               'residence_expiry_date':fields.date('Residence Expiry',required=True),
               'work_permit_date':fields.date('Work Permit'),
               'insurance_expiry_date':fields.date('Insurance date'),
               'license_date':fields.date('License date',required=True)
                             }
     def  check_eligibility(self,cr,uid,ids,context=None):
         day_obj=self.read(cr,uid,ids,['date_of_join','current_date'],context=context)
     print "day_obj#############################",day_obj
         
         calc_vacation=self.pool.get('scheme.type.info').read(cr,uid,ids,['interval','criteria','scheme_id'],context=context)
     print "day_obj#############################",calc_vacation
         
         
         dateformat="%Y-%m-%d"
         d1=datetime.strptime(day_obj[0]['date_of_join'],dateformat)
         d2=datetime.strptime(day_obj[0]['current_date'],dateformat)
         v1=d2-d1
         
         total_days=v1.days
       
         if total_days<=calc_vacation[0]['interval'] and total_days>400:
             msg=calc_vacation[0]['criteria']
         elif total_days<=calc_vacation[0]['interval']:
              msg=calc_vacation[0]['criteria']
         else:
             msg="You are not eligible"
         vals={
               'eligible_details':msg
               }
         self.write(cr,uid,ids,vals)
        
         return True

     def check_residence_expiry_date(self, cr, uid, ids, context=None):
        print "total_days#############################"
         
        expir_var=self.read(cr,uid,ids,['residence_expiry_date','current_date'],context=context)
        dateformat="%Y-%m-%d"
        d1=datetime.strptime(expir_var[0]['residence_expiry_date'],dateformat)
        d2=datetime.strptime(expir_var[0]['current_date'],dateformat)
        v1=d1-d2
        total_days=v1.days
        print "total_days#############################",total_days
        
        if total_days<=20:
            print "total_days#############################",total_days

            ir_model_data = self.pool.get('ir.model.data')
            try:
                compose_form_id = ir_model_data.get_object_reference(cr, uid, 'mail', 'email_compose_message_wizard_form')[1]
            except ValueError:
                compose_form_id = False
    
            return {
                'type': 'ir.actions.act_window',
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'mail.compose.message',
                'views': [(compose_form_id, 'form')],
                'view_id': compose_form_id,
                'target': 'new',
                'context': {},
            }
    
     def check_license_expiry(self, cr, uid, ids, context=None):
                print "total_days#############################"
                expir_var=self.read(cr,uid,ids,['license_date','current_date'],context=context)
                dateformat="%Y-%m-%d"
                d1=datetime.strptime(expir_var[0]['license_date'],dateformat)
                d2=datetime.strptime(expir_var[0]['current_date'],dateformat)
                v1=d1-d2
                total_days=v1.days
                print "total_days#############################",total_days
                
                if total_days<=20:
                    print "total_days#############################",total_days
        
                    ir_model_data = self.pool.get('ir.model.data')
                    try:
                        compose_form_id = ir_model_data.get_object_reference(cr, uid, 'mail', 'email_compose_message_wizard_form')[1]
                    except ValueError:
                        compose_form_id = False
            
                    return {
                        'type': 'ir.actions.act_window',
                        'view_type': 'form',
                        'view_mode': 'form',
                        'res_model': 'mail.compose.message',
                        'views': [(compose_form_id, 'form')],
                        'view_id': compose_form_id,
                        'target': 'new',
                        'context': {},
                    }
    
            
    
     
hr_employee()
     
class scheme_type_info(osv.osv):
    
    _name='scheme.type.info'
    
    _columns={
              'scheme_id':fields.integer('Scheme Type',required=True,size=50),
              'interval':fields.integer('interval type ',required=True,size=64),
              'criteria':fields.text('vacation criteria',required=True,size=50),
              'active':fields.boolean('Active')
              }
    
scheme_type_info()
     
     
#      if working>182
#
#  eligible for 2 ticket and 50000
#
# if working<182
#
#     eligible for 1 ticket and 30000
     

 

   .xml file------------------------

 

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>
                    
<record  model="ir.ui.view"  id="hr_employee_inherited">
                <field name="name">hr employee inherited</field>
                <field name="model">hr.employee</field>
                <field name="inherit_id"  ref="hr.view_employee_form"/>
               <field name="arch"  type="xml">
               <xpath expr=" /form/sheet/notebook/page/group/group/field[@name='active' ]"  position="after">
               <field name="date_of_join" />
               </xpath>
               
               
             <xpath expr="/form/sheet/notebook/page[@string='HR Settings']" position="after">
                <page string="Allowance Details">
                <group><field name="date_of_join"/></group>
                <group><field name="current_date"/></group>
                <group><field name="eligible_details"/></group>
                <button name="check_eligibility" string="Check Eligibility"
                                type="object" icon="gtk-apply" />
                </page>
               </xpath>
               
               <xpath expr=" /form/sheet/notebook/page[2]/group/group[4]/field[@name='birthday']"  position="after">
                           
        <group> <group><field name="visaexpiry_date" />
               <field name="residence_expiry_date" />
                <field name="work_permit_date" />
                <field name="insurance_expiry_date" />
                 <field name="license_date" /></group>
        </group>
                <group><button name="check_license_expiry" string="License Expiry"
                                type="object" icon="gtk-apply" />
                    <button name="check_residence_expiry_date" string="Residence Expiry"
                                type="object" icon="gtk-apply" /></group>
                       
               </xpath>
               </field>
 </record>
 
 
 <record id="criteria_tree_view_id" model="ir.ui.view">
                <field name="name">scheme.type.info.tree</field>
                <field name="model">scheme.type.info</field>
                <field name="arch" type="xml">
                    <tree string="Vacation Details">                                    
                        <field name="scheme_id"/>
                        <field name="interval"/>
                        <field name="criteria"/>
                        
                    </tree>
                </field>    
    </record>
    
    
    <record id="criteria_form_view_id" model="ir.ui.view">
                <field name="name">scheme.type.info.form</field>
                <field name="model">scheme.type.info</field>
                <field name="arch" type="xml">
                    <form string="Vacation Details">                                    
                        <group><field name="scheme_id"/>
                        <field name="interval"/>
                        <field name="criteria"/>
                        
                        <field name="active"/></group>
                        
                    </form>
                </field>    
    </record>
    
    
    <record id="criteria_action_id" model="ir.actions.act_window">
        <field name="name">Vacation Details</field>
        <field name="res_model">scheme.type.info</field>
        <field name="view_type">form</field>
        <field name="view_mode">tree,form</field>
        
    </record>
    
<menuitem id="menu_vacation_id" name="Vacation Details" parent="hr.menu_hr_main" action="criteria_action_id"/>
 
     
                
    </data>
</openerp>

-------------------------------------------------------

This is the error log

 

Server Traceback (most recent call last): File "/opt/openerp/server/openerp/addons/web/session.py", line 89, in send return openerp.netsvc.dispatch_rpc(service_name, method, args) File "/opt/openerp/server/openerp/netsvc.py", line 296, in dispatch_rpc result = ExportService.getService(service_name).dispatch(method, params) File "/opt/openerp/server/openerp/service/web_services.py", line 626, in dispatch res = fn(db, uid, *params) File "/opt/openerp/server/openerp/osv/osv.py", line 190, in execute_kw return self.execute(db, uid, obj, method, *args, **kw or {}) File "/opt/openerp/server/openerp/osv/osv.py", line 132, in wrapper return f(self, dbname, *args, **kwargs) File "/opt/openerp/server/openerp/osv/osv.py", line 199, in execute res = self.execute_cr(cr, uid, obj, method, *args, **kw) File "/opt/openerp/server/openerp/osv/osv.py", line 187, in execute_cr return getattr(object, method)(cr, uid, *args, **kw) File "/opt/openerp/server/openerp/addons/mecha_module/mech_info.py", line 39, in check_eligibility msg=calc_vacation[0]['criteria'] IndexError: list index out of range

 

 

 

 

0
Avatar
Descartar
Avatar
Emipro Technologies Pvt. Ltd.
Mejor respuesta

You can do before read, like

if ids:

   day_obj=self.read(cr,uid,ids,['date_of_join','current_date'],context=context)

and i see here, you use same ids for different model,

Try with above code if got problem, let me know...

0
Avatar
Descartar
ABU K
Autor

Hi ,Thanks for your replay .But I got the same error.. I think this variable data have raised the error calc_vacation=self.pool.get('scheme.type.info').read(cr,uid,ids,['interval','criteria','scheme_id'],context=context) print "day_obj#############################",calc_vacation How to redefine my code

ABU K
Autor

if ids: day_obj=self.read(cr,uid,ids,['date_of_join','current_date'],context=context) print "day_obj#############################",day_obj calc_vacation=self.pool.get('scheme.type.info').read(cr,uid,ids,['interval','criteria','scheme_id'],context=context) print "day_obj#############################",calc_vacation dateformat="%Y-%m-%d" d1=datetime.strptime(day_obj[0]['date_of_join'],dateformat) d2=datetime.strptime(day_obj[0]['current_date'],dateformat) v1=d2-d1 total_days=v1.days

Emipro Technologies Pvt. Ltd.

i think in your code there is no use of "calc_vacation", so for the testing you can move farther by putting comment on that both lines.

ABU K
Autor

No This is the purpose i want to calculate a criteria based on some date difference so first i create one model for setting the criteria and another for date calculation This the actual purpose of this code ..please read def check_eligibility(self,cr,uid,ids,context=None): day_obj=self.read(cr,uid,ids,['date_of_join','current_date'],context=context) print "day_obj#############################",day_obj calc_vacation=self.pool.get('scheme.type.info').read(cr,uid,ids,['interval','criteria','scheme_id'],context=context) print "day_obj#############################",calc_vacation dateformat="%Y-%m-%d" d1=datetime.strptime(day_obj[0]['date_of_join'],dateformat) d2=datetime.strptime(day_obj[0]['current_date'],dateformat) v1=d2-d1 total_days=v1.days if total_days400: msg=calc_vacation[0]['criteria'] elif total_days

Avatar
Ludo - 21South
Mejor respuesta

There is a lot of code there, which may or may not be relevant, but I see no stack for the error you receive. There are multiple lists you address, each of them could be causing the error.

Please post the stack itself, not just the error line.

0
Avatar
Descartar
ABU K
Autor

This the error stack----------- Server Traceback (most recent call last): File "/opt/openerp/server/openerp/addons/web/session.py", line 89, in send return openerp.netsvc.dispatch_rpc(service_name, method, args) File "/opt/openerp/server/openerp/netsvc.py", line 296, in dispatch_rpc result = ExportService.getService(service_name).dispatch(method, params) File "/opt/openerp/server/openerp/service/web_services.py", line 626, in dispatch res = fn(db, uid, *params) File "/opt/openerp/server/openerp/osv/osv.py", line 190, in execute_kw return self.execute(db, uid, obj, method, *args, **kw or {}) File "/opt/openerp/server/openerp/osv/osv.py", line 132, in wrapper return f(self, dbname, *args, **kwargs) File "/opt/openerp/server/openerp/osv/osv.py", line 199, in execute res = self.execute_cr(cr, uid, obj, method, *args, **kw) File "/opt/openerp/server/openerp/osv/osv.py", line 187, in execute_cr return getattr(object, method)(cr, uid, *args, **kw) File "/opt/openerp/server/openerp/addons/mecha_module/mech_info.py", line 39, in check_eligibility msg=calc_vacation[0]['criteria'] IndexError: list index out of rang

Ludo - 21South

Apparently sometimes your variable "calc_vacation" is empty. If you absolutely need this variable, then it would be best to raise an exeption at the beginning of your method, something like: if not calc_vacation: raise orm.except_orm('Error', 'Unable to continue, please provide calc_vacation') If it is not required, then before entering the if-statement, provide an additional check, something like so: if calc_vacation: if total_days400: msg=calc_vacation[0]['criteria'] elif total_days

OdooBot
Hi Ludo,

Here I attached my module.. and screen shot what i required exactly..so please help me to solve this error ,

error is from menu Human resources->employees->allowance details click on check eligibility button




On Wed, Jun 11, 2014 at 6:04 PM, Ludo - Neobis <ludo@neobis.nl> wrote:

Apparently sometimes your variable "calc_vacation" is empty. If you absolutely need this variable, then it would be best to raise an exeption at the beginning of your method, something like: if not calc_vacation: raise orm.except_orm('Error', 'Unable to continue, please provide calc_vacation') If it is not required, then before entering the if-statement, provide an additional check, something like so: if calc_vacation: if total_days400: msg=calc_vacation[0]['criteria'] elif total_days

--
Ludo - Neobis Sent by OpenERP S.A. using OpenERP. Access your messages and documents in Odoo



--
Thanks&Regards
Libu Koshy
¿Le interesa esta conversación? ¡Participe en ella!

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

Registrarse
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • 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 estar totalmente integrado.

Sitio web hecho con

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