Web2py Field value depends on another field - (validate while defining the model)
<p>Please consider the following table:</p>

<pre><code>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')
            )
</code></pre>

<p>Now the field 'marks_obtained' cannot have a value greater than the 'total_marks'.</p>

<p>I have tried the following</p>

<pre><code>db.bio_data.marks_obtained.requires = IS_EMPTY_OR(
IS_INT_IN_RANGE(0, db.bio_data.total_mark))
</code></pre>

<p>But this does not work. I get the following error:</p>

<pre><code>TypeError: int() argument must be a string or a number, not 'Field'
</code></pre>

<p>Any help is much appreciated.</p>

<p>You can easily do this using <code>onvalidation</code> callback function. Read this
<a href="http://www.web2py.com/books/default/chapter/29/07/forms-and-validators#onvalidation" rel="nofollow">Form and validators - onvalidation</a></p>

<p>Second solution is you need to combine '<em>Validators with dependencies</em>' and <code>IS_EXPR</code> validator. Read:</p>

<ol>
<li><p><a href="http://www.web2py.com/books/default/chapter/29/07/forms-and-validators#Validators-with-dependencies" rel="nofollow">Validators with dependencies</a></p></li>
<li><p><a href="http://www.web2py.com/books/default/chapter/29/07/forms-and-validators#IS_EXPR" rel="nofollow">IS_EXPR</a></p></li>
</ol>

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

<pre><code>is_total_less = int(request.vars.marks_obtained) &lt; 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'))
</code></pre>

<p>Make sure that <code>request.vars</code> is available.</p>

python web2py data-access-layer