Search code examples
pythonweb2pydata-access-layer

Web2py Field value depends on another field - (validate while defining the model)


Please consider the following table:

db.define_table('bio_data',
            Field('name', 'string'),
            Field('total_mark', 'integer', requires=IS_EMPTY_OR(IS_INT_IN_RANGE(0, 1e100))),
            Field('marks_obtained', 'integer')
            )

Now the field 'marks_obtained' cannot have a value greater than the 'total_marks'.

I have tried the following

db.bio_data.marks_obtained.requires = IS_EMPTY_OR(
IS_INT_IN_RANGE(0, db.bio_data.total_mark))

But this does not work. I get the following error:

TypeError: int() argument must be a string or a number, not 'Field'

Any help is much appreciated.


Solution

  • You can easily do this using onvalidation callback function. Read this Form and validators - onvalidation

    Second solution is you need to combine 'Validators with dependencies' and IS_EXPR validator. Read:

    1. Validators with dependencies

    2. IS_EXPR

    Add validator in controller something like following, I have not tested this but you will get idea from this.

    is_total_less = int(request.vars.marks_obtained) < int(request.vars.total_mark)
    
    db.bio_data.marks_obtained.requires = IS_EMPTY_OR(
    IS_EXPR('%s' % is_total_less,
            error_message='Marks Obtained should be smaller than Totak Marks'))
    

    Make sure that request.vars is available.