From 2b8a0616c774c75bc25f32d78fdbb69cbc4106f8 Mon Sep 17 00:00:00 2001 From: Olivier Dony Date: Mon, 13 Feb 2012 19:03:55 +0100 Subject: [PATCH] [ADD] field.date.context_today: added function to use as _defaults for date fields As discussed on bug 925361, in order to have a consistent behavior everywhere we need default values to be using the client's timezone, just as if the user had set the value themselves using their local clock. Because fields.date values are timezone agnostic by design, they must be correctly initialized from the start, no conversion happens later. The new context_today method is mean to be easily usable as _defaults initialize, i.e.: 'date_field': fields.date.context_today is all that is needed. It also avoids the classical mistake of forgetting to make the default value dynamic and directly passing the result of a time.strftime() call. lp bug: https://launchpad.net/bugs/925361 fixed bzr revid: odo@openerp.com-20120213180355-ruyw5j2w7r06kyue --- openerp/osv/fields.py | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/openerp/osv/fields.py b/openerp/osv/fields.py index 3e6f07cb08a..94b638e368a 100644 --- a/openerp/osv/fields.py +++ b/openerp/osv/fields.py @@ -35,14 +35,12 @@ import base64 import datetime as DT import logging +import pytz import re -import string -import sys import xmlrpclib from psycopg2 import Binary import openerp -import openerp.netsvc as netsvc import openerp.tools as tools from openerp.tools.translate import _ from openerp.tools import float_round, float_repr @@ -262,6 +260,7 @@ class float(_column): class date(_column): _type = 'date' + @staticmethod def today(*args): """ Returns the current date in a format fit for being a @@ -273,6 +272,28 @@ class date(_column): return DT.date.today().strftime( tools.DEFAULT_SERVER_DATE_FORMAT) + @staticmethod + def context_today(cr, uid, today=None, context=None): + """Returns the current date as seen in the client's timezone + in a format fit for date fields. + This method may be passed as value to initialize _defaults. + + :param datetime today: optional date value to use instead of + the current date""" + today = DT.datetime.now() + context_today = None + if context and context.get('tz'): + try: + utc = pytz.timezone('UTC') + context_tz = pytz.timezone(context['tz']) + utc_today = utc.localize(today, is_dst=False) + context_today = utc_today.astimezone(context_tz) + except Exception: + _logger.debug("failed to compute context/client-specific today date, " + "using the UTC value for `today`", + exc_info=True) + return (context_today or today).strftime(tools.DEFAULT_SERVER_DATE_FORMAT) + class datetime(_column): _type = 'datetime' @staticmethod