This question has been flagged
3 Replies
4905 Views


Link: http://stackoverflow.com/questions/32688253/python-constraints-error-message

I have written a function like below in Python. works like if user selects holiday start-date and holiday end-date with time correctly it will accepts, else it will show an error message like 'Error: Entered Invalid Date or Time'


Python code:

def _date_start_end_validate(self, cr, uid, ids, context=None):
sr_ids = self.search(cr, 1 ,[], context=context)
for self_obj in self.browse(cr, uid, ids, context=context):
if self_obj.date_start >= self_obj.date_end:
return False
return True
_constraints = [(_date_start_end_validate, 'Error: Entered Invalid Date or Time', ['Dates'])]

I need to display which start-date is showing error here, that date should to displayed.

How to get that start-date information in constraints.

Avatar
Discard
Best Answer

Supreeth,

You can raise an exception in place of "return False" statement and show your customized message there only....like:
raise osv.except_osv(_('Error:'),_('Entered Invalid Date or Time %s')%(YOUR_DATE_FIELD))

Regards

Avatar
Discard
Author

@Pawan Thanks, It is working I defined: for self_obj in self.browse(cr, uid, ids, context=context): xcv = self_obj['description'] if self_obj.date_start >= self_obj.date_end: raise osv.except_osv(_('Error:'),_('Entered Invalid Date/Time: %s')%(xcv)) return True Works fine.

Great! :)

Best Answer

Dear supreeth,

Try below code may be use full.

def _date_start_end_validate(self, cr, uid, ids, context=None):

    sr_ids = self.search(cr, 1 ,[], context=context)

    for self_obj in self.browse(cr, uid, ids, context=context):

        if self_obj.date_start >= self_obj.date_end:

            return False

    return True

def _check_msg_with_start_date(self, cr, uid, ids, context):

    data = self.browse(cr, uid, ids, context=context)

    return "Error: Entered Invalid Date or Time {} ".format(data.date_start)

_constraints = [

    (_date_start_end_validate, lambda self, *a, **kw: self._check_msg_with_start_date(*a, **kw), ['date_start','date_end'])

]

Thanks & Regards

Ankit H Gandhi

Avatar
Discard
Author

Thanks @ankit

Best Answer

def _date_start_end_validate(self, cr, uid, ids, context=None):
self_data = self.browse(cr, uid, ids[0], context=context) 
if self_data.date_start and if self_data.date_end:
start_date = datetime.strptime(self_data.date_star, DEFAULT_SERVER_DATETIME_FORMAT)
end_date = datetime.strptime(self_data.date_end, DEFAULT_SERVER_DATETIME_FORMAT)
if start_date > end_date:
return False
else:
return True
return True

_constraints = [
(_date_start_end_validate, 'Error!\nEntered Invalid Date or Time', ['date_start','date_end'])
]

Try above code may be this will help you.

Avatar
Discard