getting the name of the group a user belongs to

12 views
Skip to first unread message

adam

unread,
Nov 22, 2009, 8:21:46 AM11/22/09
to TurboGears
Hello,

I am using the TG2 authentication method and i need to get the name of
the group a user belongs too. How do i go about searching the
tg_user_group table for the group_id for the mathcing user_id and then
search the tg_group table for the name?

Jasper

unread,
Nov 22, 2009, 11:22:39 AM11/22/09
to TurboGears
The User has a groups list as attribute. Group.group_name will give
you the group name.

ex:
DBSession.query(User).first().groups[0].group_name
(assuming that the first user is member of at least one group ;) )

Kind regards,
Jasper

adam

unread,
Nov 23, 2009, 5:08:06 AM11/23/09
to TurboGears
so lets say i am updating a users authentication level i am trying to
do this

u = DBSession.query(User).filter_by(user_name=session.get
('old_username', None)).one()
u.user_name = str(kw['username'])
u.display_name = str(cgi.escape(kw['display']))
u.email_address = str(cgi.escape(kw['email']))
u.groups[0].group_id = str(cgi.escape(kw['group']))


but it throws the error IntegrityError: (IntegrityError) PRIMARY KEY
must be unique u'UPDATE tg_group SET group_id=? WHERE
tg_group.group_id = ?' ['3', 5]. What have i missed?

Christoph Zwerschke

unread,
Nov 23, 2009, 5:45:59 AM11/23/09
to turbo...@googlegroups.com
adam schrieb:
> u = DBSession.query(User).filter_by(user_name=session.get
> ('old_username', None)).one()
> u.user_name = str(kw['username'])
> u.display_name = str(cgi.escape(kw['display']))
> u.email_address = str(cgi.escape(kw['email']))
> u.groups[0].group_id = str(cgi.escape(kw['group']))
> but it throws the error IntegrityError: (IntegrityError) PRIMARY KEY
> must be unique u'UPDATE tg_group SET group_id=? WHERE
> tg_group.group_id = ?' ['3', 5]. What have i missed?

You're trying to change the primary key of an existing group. That's
probably not what you want.

The clean way would be to get the Group instance belonging to
kw['group'] (thereby also checking whether it exists), and appending it
to u.groups (optionally removing an already existing group item).

Also, as already mentioned, you don't need cgi.escape if you use the
validate decorator. Validation will also convert strings to integers
(group_id is an integer, but you're assigning it a string).

-- Christoph

rajasekhar911

unread,
Nov 23, 2009, 5:45:34 AM11/23/09
to TurboGears
u.groups[0] corresponds to the group object.

u.groups[0].group_id = str(cgi.escape(kw['group']))
in this line u r trying to change the id of the group of the user.

you have to do something like
1.remove all the groups in u.groups(if u dont want those groups)
2.find the group corresponding to kw['group']
u.groups.add(newgroup)
3.save
Reply all
Reply to author
Forward
0 new messages