Search code examples
pythonodoo

How to disable days after current date in odoo datepicker?


I have a view with a date field. The user must not select a date after today. How can I disable all days after the current date in Odoo datepicker?


Solution

  • The date picker maxDate is used to set the maximum selectable date which will disable days after the current date.

    I did not find a way to pass the current date dynamically from XML, so I overrode fields_view_get to change options attribute and set the maxDate to the current date.

    The following example set the maxDate option to the date_invoice:

    class AccountInvoice(models.Model):
        _inherit = 'account.invoice'
    
        @api.model
        def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
            res = super(AccountInvoice, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
            if view_type == 'form':
                doc = etree.XML(res['arch'])
                for node in doc.xpath("//field[@name='date_invoice']"):
                    node.set('options', "{'datepicker': {'maxDate': '%sT23:59:59'}}" % fields.Date.today().strftime(DEFAULT_SERVER_DATE_FORMAT))
                res['arch'] = etree.tostring(doc)
            return res
    

    Edit:

    You can use or inside the XPATH expression to specify the second field name.

    doc.xpath("//field[@name='date_invoice' or @name='date_due']")
    

    Edit:

    Try to specify a time at 23:59:59

    node.set('options', "{'datepicker': {'maxDate': '%sT23:59:59'}}" % fields.Date.today().strftime(DEFAULT_SERVER_DATE_FORMAT))