Reputation: 453
I added two fields to project module, start_date and stop_date. And I tried to add a code that controls the input and only saves the record if stop_date is greater than start_date. So I added this code to the project class:
date_start = fields.Date(string='Start Date')
date_stop = fields.Date(string= 'Deadline')
@api.onchange('date_stop')
def _onchange_date_stop(self):
if self.date_start != False and self.date_stop != False:
if (self.date_stop<=self.date_start):
raise ValidationError("deadline date Should be greater than start date!")
_constraints = [
(_onchange_date_stop, 'deadline date 2 Should be greater than start date!', []),
]
Now when the deadline is before the start date, it raises validation error:
deadline date Should be greater than start date!
and when I try to save the record I got this error:
deadline date 2 Should be greater than start date!
Error details:
deadline date Should be greater than start date!
None
But when the deadline is greater than the start date, I got this error:
deadline date 2 Should be greater than start date!
So I always have a problem, whether if the deadline was greater or not than the start date.
Anybody can help? Thanks.
Upvotes: 0
Views: 344
Reputation: 133
Other than onchange we can use constraints... It helps to validate something when create and edit and also in change.. Here is my code and it works fine
date_start = fields.Date(string='Start Date')
date_stop = fields.Date(string= 'Deadline')
@api.multi
@api.constrains('date_start', 'date_stop')
def _check_date(self):
date_start = self.date_start
date_stop = self.date_stop
if (date_start and date_stop) and (date_start > date_stop):
raise ValidationError(_('The start date must be less than to the end date. ')
Upvotes: 1
Reputation: 453
Also this code worked for me too:
date_start = fields.Date(string='Start Date')
date_stop = fields.Date(string= 'Deadline')
@api.one
@api.constrains('date_start', 'date_stop')
def _check_deadline(self):
if self.date_stop <= self.date_start:
raise ValidationError("deadline must be greater than start date")
Upvotes: 0
Reputation: 234
You can use constrain decorator
@api.constrains('date_start', 'date_stop')
def check_date_fields(self):
if self.date_start and self.date_stop:
if self.date_stop <= self.date_start:
raise ValidationError("deadline date Should be greater than start date!")
Upvotes: 1