tjr tjr - 7 days ago 5
Python Question

web2py validating db model for group menbers

I am using web2py, and am trying to build a field for auth_user, that should be validated to be a member of a certain group. So, in the models/db.py I have added a field that tells who is the manager of the user:

auth.settings.extra_fields['auth_user']=[Field('manager', 'reference auth_user')]


Then I have set up to
db.auth_user
,
db.auth_group
and
db.auth_membership
to contain users that belong to group 'managers'

And what I would like now to achieve is to validate user input so, that the 'manager' field of the
auth_user
could contain only users from the group 'managers'. I have gone through quite a few variations, following is maybe closest to making sense in theory in my mind:

group_id = auth.id_group('managers')
all_users_in_group = db(db.auth_membership.group_id==group_id)._select(db.auth_membership.user_id)
db.auth_user.auditor.requires = IS_IN_DB(db, db(~db.auth_user.id.belongs(all_users_in_group)).select(db.auth_user.id))


But even that is failing with

<type 'exceptions.AttributeError'>('Table' object has no attribute 'managers')


A perfect solution to my problem would show in the drop down menu not
auth_user.id
, but
auth_user.first_name
concatenated with
auth_user.last_name
.

Answer

You have done it correctly in your answer, but you can improve it.

The first argument of the validator can be a database connection or a DAL Set. So you can pass directly a db query as first argument, like this

query = db((db.auth_membership.group_id == auth.id_group('managers')) &
           (db.auth_membership.user_id == db.auth_user.id))
db.auth_user.auditor.requires = IS_IN_DB(query, db.auth_user.id, '%(first_name)s %(last_name)s')

You can also write query like below:

query = db((db.auth_group.role == 'managers') &
           (db.auth_membership.group_id == db.auth_group.id) &
           (db.auth_membership.user_id == db.auth_user.id))
Comments