Search code examples
datedatetimeodoocrm

Add days to a datetime and convert it to a date ? - Odoo V14


i want to add 30 days to a datetime field and make my date field take this value as default.

I tried this, but don't work :/


from odoo import models, fields, api
from datetime import datetime
from dateutil.relativedelta import relativedelta

class crm_lead(models.Model):
    _inherit = 'crm.lead'
    
    date_deadline = fields.Datetime(string='Fermeture prévue')
    
    @api.onchange('create_date')
    def _onchange_enddate(self):
        if self.create_date:
            date_end = ( datetime.strptime(self.create_date, '%Y-%m-%d') + relativedelta(days =+ 30).strftime('%Y-%m-%d') )
            self.date_deadline = date_end.date()

Thanks by advance !


Solution

  • The create_date is a magic field set in _create method. To use the creation date as a default value for the date_deadline field, you can use the default attribute and use the Date.today function to get the creation date.

    Example:

    date_deadline = fields.Datetime(default=lambda record: fields.Date.today() + relativedelta(days=30))