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()返回 [<Group: Editor>]。
或者,也可以更直接地通过以下方式检查用户是否在组中:
if django_user.groups.filter(name = groupname).exists():
...
def is_allowed(user):
allowed_group = set(['admin', 'lead', 'manager'])
usr = User.objects.get(username=user)
groups = [ x.name for x in usr.groups.all()]
if allowed_group.intersection(set(groups)):
return True
return False
from django.contrib.auth.decorators import login_required, user_passes_test
@login_required
@user_passes_test(is_member) # or @user_passes_test(is_in_multiple_groups)
def myview(request):
# Do your processing
对于基于类的视图,可以使用 UserPassesTestMixin和 test_func方法:
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class MyView(LoginRequiredMixin, UserPassesTestMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
def test_func(self):
return is_member(self.request.user)
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.groups.filter(name='companyGroup').exists())
def you_view():
return HttpResponse("Since you're logged in, you can see this text!")