auth_membership grid with both, group id and group roles displayed when adding a new record

57 views
Skip to first unread message

Vlad

unread,
Oct 7, 2019, 2:05:00 AM10/7/19
to web2py-users
the following line works perfectly: 

grid = SQLFORM.grid(db.auth_membership)

by "perfect" in the context, I mean that when I click "add record", the group id field contains both values, group id and group role (for example, "Manager (4)", "Loyal customer (9)", ... 

However, I want to limit what kind of membership a user can create, so here is what I do: 

   ids = [1,3,5]
   db.auth_membership.group_id.requires = IS_IN_SET(ids)
   grid = SQLFORM.grid(db.auth_membership)

This indeed limits group id field value that a user can specify when creating a new record. When clicking "Add record", the group id field is represented by a drop-down with the values "1, 3, 5", as expected. 

The problem is that now when limited to 1, 3, and 5, no roles are displayed. Only group id integer values are (to reiterate, without this limitation to 1,3,5 the drop-down contains both, group id and group role for each line, for all the groups). 

How can I ensure that the roles are also displayed, in addition to group ids, on add record, when using  requires=IS_IN_SET ? 

Annet

unread,
Oct 7, 2019, 6:36:02 AM10/7/19
to web2py-users
Use IS_IN_DB()

   ids = [1,3,5]


db.auth_membership.group_id.requires = IS_IN_DB(db(db.auth_group.id.belongs(ids)), 'auth_group.id', '%(role)s')


Best,

Annet

villas

unread,
Oct 7, 2019, 6:38:24 AM10/7/19
to web2py-users
By specifying requires = IS_IN_SET(ids), you are also overriding the represent too.

See below, I hope it will point you in the right direction:

mygroupdict = {1:'Public',2:'Private',3:'Admin'}
db.auth_membership.group_id.requires = IS_IN_SET(mygroupdict,zero=None))
db.auth_membership.group_id.represent = lambda group_id, row: mygroupdict[group_id]

Vlad

unread,
Oct 7, 2019, 5:12:01 PM10/7/19
to web2py-users
thank you very much! 
works like a charm! 

Vlad

unread,
Oct 7, 2019, 5:14:48 PM10/7/19
to web2py-users
I don't fully understand it - will play with it to figure it out. 
Annet's suggestion worked right away, but still I really want to understand what's going on...
thank you!  

Annet

unread,
Oct 8, 2019, 2:55:14 AM10/8/19
to web2py-users
Hi Villas,

Will your solution still work when you change the value of role in the auth_membership table? In your mygroupdict you define the role values again, so that there is no single point of definition.

I may be wrong but isn't that something to keep in mind when using your solution?


Best Annet

villas

unread,
Oct 8, 2019, 7:00:01 AM10/8/19
to web2py-users
Hi Annet
You are right, and my example was indeed 'hard-coded'.
However, it was not really intended as a final solution.  As with any contributions I make, I simply try to illuminate 'a way ahead'.
If someone makes a better solution, I can also learn!
Many thanks.
Reply all
Reply to author
Forward
0 new messages