How to declare _constraints for an OpenERP model?

223 Views Asked by At

I created a new model:

class rpe_mandate(orm.Model):
    _name = 'rpe.mandate'

    def _check_dates(self, cr, uid, ids, context=None):
        for rec in self.browse(cr, uid, ids):
            delivery_date = rec.delivery_date
            receipt_date = rec.receipt_date
            if delivery_date > receipt_date:
                return False
        return True

    _columns = {
        'delivery_date': fields.date('Delivery date'),
        'receipt_date': fields.date('Receipt date'),
    }

    _constraints = [
        (_check_dates, 'Error! Delivery date must be earlier than receipt date.', ['delivery_date', 'receipt_date',])
    ]

What I want is to show an error message if the receipt date is earlier than the delivery date.

But with my code, nothing is happening when I save a record, in both cases (if the receipt date is earlier than the delivery date and the other way around -- I tried it too to check if I did it wrong --)

2

There are 2 best solutions below

0
On BEST ANSWER

You were generating a new record for rpe_mandate, but through a many2many field. So, when you clicked on "Save" in the popup, it wasn't being stored in the database. You have to click on button "Save", but in the main form, to see the error message.

3
On

Try this code

def _check_dates(self, cr, uid, ids, context=None):
    for rec in self.browse(cr, uid, ids):
        delivery_date = rec.delivery_date
        receipt_date = rec.receipt_date
        if delivery_date > receipt_date:
            raise osv.except_osv(_("Alert !!"),_("Delivery date must be earlier than receipt date"))
    return True

Dont forget to import

from openerp.tools.translate import _