DB model reference field conditions eg. auth_user belonging to a certain group only

27 views
Skip to first unread message

Oasis Agano

unread,
Jan 12, 2018, 4:13:07 AM1/12/18
to web2py-users
Greetings,


I have defined a table referencing auth_user, but i want on the web form select box to only bring users belonging to one group,
not showing all the system users.

i am wondering if i should use a lambda function or if there is a way of adding a condition on a reference field.

E,g returning only users belonging in a writer group on the writer_user

db.define_table('post',
                Field('post_name','string', label="Name", requires=IS_NOT_EMPTY()),
                Field('description','text', label="Desc"),
                Field('writer_user','reference auth_user', label="User"),
                auth.signature,
                format='%(post_name)s')

Kr,

Oasis

tim.n...@conted.ox.ac.uk

unread,
Jan 12, 2018, 6:58:33 AM1/12/18
to web...@googlegroups.com
You can put conditions into the field validator:

    Field('writer_user', 'reference auth_user', 
        requires=IS_IN_DB(
            db(
                (db.auth_user.id == db.auth_membership.user_id)
                & (db.auth_membership.group_id == db.auth_group.id)
                & (db.auth_group.role == 'your group here')
            ),
            db.auth_user.id
    )

Anthony

unread,
Jan 12, 2018, 10:22:14 AM1/12/18
to web2py-users
On Friday, January 12, 2018 at 6:58:33 AM UTC-5, tim.n...@conted.ox.ac.uk wrote:
You can put conditions into the field validator:

    Field('writer_user', 'reference auth_user', 
        requires=IS_IN_DB(
            db(
                (db.auth_user.id == db.auth_membership.user_id)
                & (db.auth_membership.group_id == db.auth_group.id)
                & (db.auth_group.role == 'your group here')
            ),
            db.auth_user.id
    )


And note, if you explicitly specify the "requires" argument for a reference field, you will lose the default "represent" function, so you must explicitly specify that as well.

Anthony
Reply all
Reply to author
Forward
0 new messages