Skip to content
Advertisement

Override create method to Restrict user from creating a new record based on condition Odoo13

I want to restrict the user from creating a new record on a model based on a specific condition. for instance, I have two fields in the model both of them is Integer (move_item_count,item_number ) and they are computed field I compute their values. If their move_item_count != item_number I should prevent the user from creating the record and raise an error message. here is my code it gives me this error ‘NoneType’ object has no attribute ‘id’. enter image description here here is my code :

 # Overriding the Create Method in Odoo
@api.model
def create(self, vals):
    # overriding the create method to add the sequence and prevent the  user from
    # creating a new record if a condition didn't fulfilled
    for rec in self:
        if rec.move_item_count != rec.item_number:
            raise UserError(_("Some Item Are Missing."))
        if vals.get('name', _('New')) == _('New'):
            vals['name'] = self.env['ir.sequence'].next_by_code('move.sequence') or _('New')
        result = super(LogisticMove, self).create(vals)
        return result

Advertisement

Answer

Overriding the create is not recommended when applying a constraint on creation of a record as this can get really messy when 2 or more modules override the same create. You’d be better off using actual constraints (see doc right here for example).

If you feel like you must, then keep in mind that until the actual create (the super) has been called, the record is NOT in the database and also NOT present in self. All you have to go with are the values for creating this which are stored in your vals parameter.

If you inspect those values you can do the comparison and provide feedback to the user.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement