Django权限与分组

from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType


g = Group(name='group_test') #创建一个组
g.save()

g = Group.objects.get(name='group_test') #获取存在的组

content_type = ContentType.objects.get_for_model(ViewPermission) # ViewPermission为models.py中的一个类
class ViewPermission(models.Model):
    class Meta:
        permissions = (
            ('ych_order', 'xxx'),
        )

p = Permission.objects.create(codename='view_ych', name='Can see ych', content_type=content_type) #创建权限

p = Permission.objects.get(codename='view_ych') #获取已存在的权限

g.permissions.add(p) #为组g添加权限p

user.groups.add(g) #将用户user添加到组g

user.has_perm('report.view_ych') #判断权限