如何在Odoo的日期时间选择器中访问前一天的日期和今天的日期?

时间:2015-08-06 05:44:17

标签: python-2.7 datetime odoo odoo-8 openerp-8

我正在尝试检查今天的日期只能在Odoo的日期时间选择器中被选中的条件,代码如下。

def onchange_date(self, cr, uid, ids, fdate, context=None):
if fdate:
if datetime.strptime(fdate, "%Y-%m-%d %H:%M:%S").date() <> 
datetime.now().date():
return { 'value': { 'fdate': False } }
return fdate

我还想让前一天,即昨天的日期可供用户选择以及今天的日期。

2 个答案:

答案 0 :(得分:1)

selected_date = datetime.strptime(fdate, "%Y-%m-%d %H:%M:%S").date()
yes_date = datetime.strptime(fdate, "%Y-%m-%d %H:%M:%S").relativedelta(days = -1).date()
today = datetime.now().date()
if selected_date <> today and selected_date <> yes_date

并添加相对delte的导入文件

答案 1 :(得分:1)

如果您只使用日期,则应使用date代替datetime,如果您只希望用户使用今天的日期,则首先自动获取今天的日期并将其{ {1}},像这样:

readonly

如果你想要一个用户只能选择昨天和今天的日子,那会更费力,我知道这不是最好的方法,但它运作正常。

...
import time
...
#here you got a field with the date of today.
date_today = fields.Date('Today is: ', default = lambda *a: time.strftime("%Y-%m-%d"), readonly = True)

修改

我只使用V8,但我知道一些V7语法!

1号。

...
from openerp.exceptions import ValidationError
...

chosen_date = fields.Date('Chosen day: ', default = lambda *a: time.strftime("%Y-%m-%d"))

@api.onchange('chosen_date'):
def _onchange_chosen_date(self):
    yesterday = str( int(time.strftime("%d")) - 1 )
    if len(yesterday) == 1:
        yesterday = '0' + yesterday
    yesterday_date = time.strftime("%Y-%m-" + yesterday)
    if self.chosen_date != time.strftime("%Y-%m-%d") or self.chosen_date != yesterday_date:
        return { 'warning': {'title':"Warning", 'message':"You are only able to choose only yesterday and today...!"}}

二路。

...
import time
...
#here you got a field with the date of today.
date_today = fields.date('Today is: ', default = lambda *a: time.strftime("%Y-%m-%d"), readonly = True)

在XML中:

...
from openerp.osv import osv
...

chosen_date = fields.date('Chosen day: ', default = lambda *a: time.strftime("%Y-%m-%d"))

def _onchange_chosen_date(self, cr, uid, ids, chosen_date, context=None):
    yesterday = str( int(time.strftime("%d")) - 1 )
    if len(yesterday) == 1:
        yesterday = '0' + yesterday
    yesterday_date = time.strftime("%Y-%m-" + yesterday)
    if self.chosen_date != time.strftime("%Y-%m-%d") or self.chosen_date != yesterday_date:
        raise osv.except_osv(("Warning"),("You are only able to choose only yesterday and today...!"))

我希望这对你有所帮助!!!