Start Date and End Date Based on Selected Month

Geminate Consultancy Services

Sometimes we need to auto fill start date and end date on our apps based on month selected. This blog will help to get this job quick and fast.

Suppose we have a case where we have these fields

  • Month Selection field

  • year an integer field

  • Duration which is start date of month and end date of month 

Definition of these fields in New API

month = fields.Selection(MONTH_LIST, string='Month', required=True, default=MONTH_LIST[int('%m'))-1])

    Here MONTH_LIST defined as global variable 

    MONTH_LIST= [('1', 'Jan'), ('2', 'Feb'), ('3', 'Mar'), ('4', 'Apr'), ('5', 'May'), ('6', 'Jun'), ('7', 'Jul'), ('8', 'Aug'), ('9', 'Sep'), ('10', 'Oct'), ('11', 'Nov'),('12', 'Dec')]


    will autofill month field with current month

year = fields.Integer('Year', required=True,'%Y'))'%Y')

    will autofill year field with current year

date_from = fields.Date('Date From', required=True)

date_to = fields.Date('Date To', required=True)

Now to update date from and date to with start date of month and end date of month on month onchange here is the simple onchange method.

from datetime import datetime, date

import calendar


    def onchange_month(self):

        if self.month:

              month_date = date(self.year, int(self.month), 1)

              self.date_from = month_date.replace(day = 1)

              self.date_to = month_date.replace(day = calendar.monthrange(month_date.year, month_date.month)[1])