2

I have a user table 'UserInfo' and created two groups 'admin' and 'normal users' given some permissions to these groups.

I am adding the users to a particular group based on the type of the user i.e if user is admin I will give the permissions of the admin to that user.

Now I want to check whether a particular user has_perm or not, and also I want to add the user to the table auth_user_group. How can I do this?

4

1 回答 1

0

每个用户都有一个groupsManyToManyManager 来列出他们的组。如果要将用户添加到组,请使用ManyToManyManagerapi

u = User.objects.get(pk=1)
g = Group.objects.get(name='admin')
u.groups.add(g)
u.save()
u.groups.remove(g)
u.save()

将用户添加到组后,他们将继承该组的所有权限。没有等效的has_perm检查用户是否在组中,但是user_passes_test您可以使用它来检查用户是否通过任何条件。它通过调用您使用用户对象定义的任何函数来工作:

from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render

def is_admin(user):
   return user.group_set.filter(name='admin').count()

@user_passes_test(is_admin)
def only_admin(request):
    return render(request, 'sekret.html')
于 2013-11-06T05:09:04.283 回答