在Django中,如何检查用户是否在某个组中? [英] In Django, how do I check if a user is in a certain group?
本文介绍了在Django中,如何检查用户是否在某个组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Django的管理员网站中创建了一个自定义组。
I created a custom group in Django's admin site.
在我的代码中,我想检查一个用户是否在这个组中。如何做?
In my code, I want to check if a user is in this group. How do I do that?
推荐答案
您可以通过组
用户中的$ c>属性。
You can access the groups simply through the groups
attribute on User
.
from django.contrib.auth.models import User, Group
group = Group(name="Editor")
group.save() # save this new group for this example
user = User.objects.get(pk=1) # assuming, there is one initial user
user.groups.add(group) # user is now in the "Editor" group
然后 user.groups.all()
返回 [<组:编辑器> ;]
这篇关于在Django中,如何检查用户是否在某个组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文