creamidea / Mushroom

To display Node Capture Data and Control it
Other
0 stars 1 forks source link

Django 增加一个用户到一个组中 #5

Open creamidea opened 10 years ago

creamidea commented 10 years ago
from django.contrib.auth.models import Group
g = Group.objects.get(name='groupname') 
g.user_set.add(your_user)

link issue #1

creamidea commented 10 years ago

django增加一个组:

from django.contrib.auth.models import User,Group

# Get or Create the Group (I <3 this method)
mygroup, created = Group.objects.get_or_create(name='Web Design')

# Add fakeuser to group
myuser = User.objects.get(username='fakeuser')
myuser.groups.add(mygroup)

或者

from django.contrib.auth.models import Group as DjangoGroup
gUsers = DjangoGroup(name='Users')
gUsers.save()
gGroupAdmins = DjangoGroup(name='GroupAdmins')
gGroupAdmins.save()

# Set users
zen = User.objects.create_user('zen', 'zen@emailaddress','pwd123')
zen.groups = [gUsers]
creamidea commented 10 years ago

列出一个组中拥有某个权限的所有的用户


from django.contrib.auth.models import User, Permission
from django.db.models import Q

perm = Permission.objects.get(codename='blogger')  
users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm) ).distinct()

或者

from django.contrib.auth import models

group = models.Group.objects.get(name='blogger')
users = group.user_set.all()

参考:http://stackoverflow.com/questions/378303/how-to-get-a-list-of-all-users-with-a-specific-permission-group-in-django