I tried to evaluate a python code that i write it in a text field.
this is the error that i face
TypeError: unsupported operand type(s) for %: 'ValidationError' and 'exceptions.ValueError'
First of all i have this class condition:
class condition(models.Model):
_name = 'condition'
expression_cond = fields.Selection(
string="Expression",
selection=[('python', 'Expression Python'), ],
required=True,
default="python")
value_cond = fields.Text(
string="Valeur",
required=True,
default="""
# Python code.
# You can use the following variables :
# - self: ORM model of the record which is checked
# - object: same as order or line, browse_record of the sale order or
# - pool: ORM model pool (i.e. self.pool)
# - cr: database cursor
# - context: current context
# - invoice: test for invoice tests
# Note: returned value have to be set in the variable 'result'
"""
)
name = fields.Char(string="Condition", required=True, )
The second class is the rules; i create this calss to select a condition and to verifier if the python expression is correct
class rules(models.Model):
_name = 'rules'
name = fields.Char(string="Régles" ,required=True)
code = fields.Char(string="Code" ,required=True)
condition_id = fields.Many2one(comodel_name="condition", string="Condition ", required=True, )
amount_type_id = fields.Many2one(comodel_name="amount.type", string="Méthode de Calcul", required=True, )
i create those method in this class
@api.model
def _rules_eval_context(self, obj_name, rec):
invoice = self.env['account.invoice']
return {obj_name: rec,
'invoice': invoice,
'self': self.pool.get(rec._name),
'object': rec,
'obj': rec,
'pool': self.pool,
'cr': self._cr,
'uid': self._uid,
}
@api.model
def _rule_eval(self,rule, obj_name, rec):
rule =self.condition_id.value_cond
expr = rule
space = self._rules_eval_context(obj_name, rec)
)
try:
safe_eval(expr,
space,
mode='exec',
nocopy=True) # nocopy allows to return 'result'
except Exception as e:
raise ValidationError("Wrong python code defined for Condition : %s") % (e)
return space.get('result', False)@api.onchange('condition_id')
def _detect_rules(self):
rule = self.condition_id.value_cond
if self._rule_eval(rule,'invoice', self):
print("*****dectect rules")
else:
print("*********wrong detection")
this is my expression that i creat
if invoice.amout_total >=1000 : result=True
you can find the pictures on this link
https://drive.google.com/drive/folders/0BwRD3KEH7ZiVS0VFemxTNjJkSHc?usp=sharing
ff