odooodoo-8odoo-10

odoo8 Field year selection with today year as default


I want to make a year selection where the default year is now.
This is my .py

def get_years():
    year_list = []
    for i in range(2022, 2036):
        year_list.append((i, str(i)))
    return year_list    

def get_year(self):
    return str(datetime.now().year)

year = fields.Selection(get_years(), string='Year', default=get_year)

and this is my .xml

<field name="year">

But I get this error

ValueError: Wrong value for wizard.report.purchase.tracking.year: '2023'

What should I do?
Thank you for your help


Solution

  • You have to set the string type key and pair value of touple for the selection field.

    def get_years():
        year_list = []
        for i in range(2022, 2036):
            year_list.append((str(i), str(i)))
        return year_list
    

    also You can set default value directly at selection.

    year = fields.Selection(get_years(), string='Year', default=str(datetime.now().year))