有没有一种简单的方法来获取用户在Django的组名 [英] is there a simple way to get group names of a user in django

查看:302
本文介绍了有没有一种简单的方法来获取用户在Django的组名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 django.contrib.auth.User django.contrib.auth.Group

I tried following Code with the help of the django.contrib.auth.User and django.contrib.auth.Group

for g in request.user.groups:
    l.append(g.name)

但是失败了,我收到以下错误

But that failed and I received following Error:

TypeError at /
'ManyRelatedManager' object is not iterable
Request Method: GET
Request URL:    http://localhost:8000/
Exception Type: TypeError
Exception Value:    
'ManyRelatedManager' object is not iterable
Exception Location: C:\p4\projects\...\users.py in permission, line 55

感谢您的帮助!

推荐答案

您可以使用 request.user.groups.all()获取用户组,这将返回 QuerySet 。然后,您可以根据需要将该对象转换为列表。

You can get the groups of a user with request.user.groups.all(), which will return a QuerySet. And then you can turn that object into a list if you want.

for g in request.user.groups.all():
    l.append(g.name)

或与最近的Django

or with recent Django

l = request.user.groups.values_list('name',flat = True) # QuerySet Object
l_as_list = list(l)                                     # QuerySet to `list`

这篇关于有没有一种简单的方法来获取用户在Django的组名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆