django分组groupuserpermission

Posted harrytree

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django分组groupuserpermission相关的知识,希望对你有一定的参考价值。

1、创建app01/models.py下User模型

from django.db import models
from django.contrib.auth.models import   BaseUserManager, AbstractBaseUser, PermissionsMixin
from django.contrib.auth import get_user_model

class UserManager(BaseUserManager):
    def _create_user(self , telephone, username, password, **kwargs):
        if not telephone:
            raise  ValueError("必须要传递手机号码!")
        if not password:
            raise  ValueError("必须要传递密码")
        user = self.model( telephone = telephone, username= username , **kwargs)
        user.set_password( password )
        user.save()
        return  user

    def create_user(self,  telephone, username, password, **kwargs):
        kwargs[is_superuser] = False
        return self._create_user( telephone = telephone, username=username, password = password, **kwargs )

    def create_superuser(self, telephone, username, password, **kwargs):
        kwargs[is_superuser] = True
        return  self._create_user( telephone = telephone, username=username, password = password, **kwargs )

class User(AbstractBaseUser, PermissionsMixin):
    telephone = models.CharField(max_length=11, unique=True)
    email = models.CharField(max_length=100, unique=True)
    username = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)

    USERNAME_FIELD = "telephone"   #USERNAME_FIELD作用,是执行authenticate验证, username参数传入后,实际校验的是telephone字段
    REQUIRED_FIELDS = []

    objects = UserManager()

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    # author = models.ForeignKey(  User, on_delete= models.CASCADE )
    #get_user_model()会自动获取settings.py里面 AUTH_USER_MODEL,这样不管你定义的那个User,都可以自动获取,更安全
    author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)

    class Meta:
        permissions =[
            (view_article, 看文章的权限!),
        ]

 

2、在app01/views.py里面,通过视图operate_group,   添加分组、分组添加对应的权限、用户添加到分组里面、查询用户的权限

from django.shortcuts import render, HttpResponse, reverse,redirect
from django.db import  connection
from app01.models import User, Article
from django.contrib.auth import  authenticate, login, logout
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import Permission, ContentType, Group
from app01.forms import LoginForm


def test(request):
    #创建用户
    User.objects.create_user( telephone="15555655555", password="555555", username="zhiliao5" )

    #用认证
    # user = authenticate(request, username="15555655555", password="555555")
    # if user:
    #     print(user.username)
    #     print("验证成功!")
    # else:
    #     print("验证失败!")
    return  HttpResponse("继承AbstractUser扩展用户")


def my_login(request):

    if request.method == "GET":
        return render(request, "login.html")
    else:
        print("提交的数据为:"); print(request.POST)
        form = LoginForm(request.POST)
        if form.is_valid():
            telephone = form.cleaned_data.get("telephone")
            password = form.cleaned_data.get("password")
            remember = form.cleaned_data.get("remember")
            user = authenticate(request, username =telephone, password=password)
            if user and user.is_active:
                login(request, user)
                if remember:
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)
                #判断是否有next跳转地址
                if request.GET.get("next"):
                    return redirect( request.GET.get("next") )
                return HttpResponse("登录成功!")
            else:
                return  HttpResponse("手机号码或者密码错误!")
        else:
            print(form.errors)
            return redirect( reverse("login") )

def my_logout(request):
    logout(request)
    return HttpResponse("成功退出")

@login_required(login_url="/login/")
def profile(request):
    return HttpResponse("这是个人中心,只有登录了以后才能查看到!")

#添加权限
def add_permission(request):
    content_type = ContentType.objects.get_for_model( Article)
    permission = Permission.objects.create( codename="black_article", name="拉黑文章", content_type=content_type )
    return HttpResponse("权限创建成功")

#用户与权限
def operate_permission(request):
    user = User.objects.first()
    content_type = ContentType.objects.get_for_model(Article)
    permissions = Permission.objects.filter( content_type = content_type )
    for permission in permissions:
        print(permission)
    #set([])添加权限
    user.user_permissions.set(permissions)
    #清空权限
    # user.user_permissions.clear()
    #add(*[])添加权限
    # user.user_permissions.add(* permissions)
    #remove(*[])删除权限
    # user.user_permissions.remove(*permissions)

    if user.has_perm(app01.view_article):
        print("这个用户拥有view_article权限")
    else:
        print("这个用户没有view_article权限")
    print( user.get_all_permissions())
    return HttpResponse("操作权限的视图!")

#权限限制
# def add_article(request):
#     if request.user.is_authenticated:
#         print("已经登录了")
#         if request.user.has_perm(‘app01.add_article‘):
#             return HttpResponse("这是添加文章的页面!")
#         else:
#             return HttpResponse("您没有访问页面的权限!", status=403)
#     else:
#         return redirect( reverse("login"))

#permission_required做了两件事
#1.如果没有登录,会跳转到登录页面
#2.如果没有权限,通过 raise_exception=True,会显示 403 Forbidden错误页面
@permission_required( app01.add_article, login_url=/login/, raise_exception=True)
def add_article(request):
    return HttpResponse("这是添加文章的页面!")


def operate_group( request ):
    # 添加‘运营组‘,并给‘运营组‘添加上Article相关的权限
    # group = Group.objects.create(name="运营")
    # content_type = ContentType.objects.get_for_model(Article)
    # permissions = Permission.objects.filter(  content_type=content_type )
    # group.permissions.set( permissions )

    # print( connection.queries)
    ‘‘‘ 
        访问http://127.0.0.1:8080/oper_group 后,打印,执行的源来sql如下:
        [{‘sql‘: ‘SELECT @@SQL_AUTO_IS_NULL‘, ‘time‘: ‘0.000‘},
        {‘sql‘: ‘SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED‘, ‘time‘: ‘0.001‘},
        {‘sql‘: "INSERT INTO `auth_group` (`name`) VALUES (‘运营‘)", ‘time‘: ‘0.631‘}, 
        {‘sql‘: ‘SELECT VERSION()‘, ‘time‘: ‘0.000‘},
        {‘sql‘: "SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = ‘app01‘ AND `django_content_type`.`model` = ‘article‘)", ‘time‘: ‘0.189‘}, 
        {‘sql‘: ‘SELECT `auth_permission`.`id`, `auth_permission`.`name`, `auth_permission`.`content_type_id`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`) WHERE `auth_permission`.`content_type_id` = 7 ORDER BY `django_content_type`.`app_label` ASC, `django_content_type`.`model` ASC, `auth_permission`.`codename` ASC‘, ‘time‘: ‘0.047‘},
        {‘sql‘: ‘SELECT `auth_permission`.`id` FROM `auth_permission` INNER JOIN `auth_group_permissions` ON (`auth_permission`.`id` = `auth_group_permissions`.`permission_id`) INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`) WHERE `auth_group_permissions`.`group_id` = 1 ORDER BY `django_content_type`.`app_label` ASC, `django_content_type`.`model` ASC, `auth_permission`.`codename` ASC‘, ‘time‘: ‘0.031‘},
        {‘sql‘: ‘SELECT `auth_group_permissions`.`permission_id` FROM `auth_group_permissions` WHERE (`auth_group_permissions`.`group_id` = 1 AND `auth_group_permissions`.`permission_id` IN (19, 20, 21, 22, 26))‘, ‘time‘: ‘0.002‘}, 
        {‘sql‘: ‘INSERT INTO `auth_group_permissions` (`group_id`, `permission_id`) VALUES (1, 19), (1, 20), (1, 21), (1, 22), (1, 26)‘, ‘time‘: ‘0.013‘}]

    ‘‘‘
    # group.save()

    #给用户添加到‘运营组‘
    # group = Group.objects.filter( name="运营" ).first()
    # user = User.objects.first()
    # user.groups.add( group)
    # user.save()
    # print(connection.queries)
    ‘‘‘
    执行源sql如下:
    [{‘sql‘: ‘SELECT @@SQL_AUTO_IS_NULL‘, ‘time‘: ‘0.000‘}, 
    {‘sql‘: ‘SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED‘, ‘time‘: ‘0.000‘}, 
    {‘sql‘: ‘SELECT VERSION()‘, ‘time‘: ‘0.001‘}, 
    {‘sql‘: ‘SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED‘, ‘time‘: ‘0.000‘}, 
    {‘sql‘: "SELECT `auth_group`.`id`, `auth_group`.`name` FROM `auth_group` WHERE `auth_group`.`name` = ‘运营‘ ORDER BY `auth_group`.`id` ASC LIMIT 1", ‘time‘: ‘0.001‘}, 
    {‘sql‘: ‘SELECT `app01_user`.`id`, `app01_user`.`password`, `app01_user`.`last_login`, `app01_user`.`is_superuser`, `app01_user`.`telephone`, `app01_user`.`email`, `app01_user`.`username`, `app01_user`.`is_active` FROM `app01_user` ORDER BY `app01_user`.`id` ASC LIMIT 1‘, ‘time‘: ‘0.001‘}, 
    {‘sql‘: ‘SELECT `app01_user_groups`.`group_id` FROM `app01_user_groups` WHERE (`app01_user_groups`.`group_id` IN (1) AND `app01_user_groups`.`user_id` = 1)‘, ‘time‘: ‘0.019‘}, 
    {‘sql‘: ‘INSERT INTO `app01_user_groups` (`user_id`, `group_id`) VALUES (1, 1)‘, ‘time‘: ‘0.010‘}, 
    {‘sql‘: "UPDATE `app01_user` SET `password` = ‘pbkdf2_sha256$100000$h7RXXVD8QB0M$22q4FGAiYtwrm7hMRLqHsOYTlVD2G9OgJKMkRyYd28I=‘, `last_login` = ‘2019-11-09 06:55:07.151812‘, `is_superuser` = 0, `telephone` = ‘15555655555‘, `email` = ‘‘, `username` = ‘zhiliao5‘, `is_active` = 1 WHERE `app01_user`.`id` = 1", ‘time‘: ‘0.008‘}]

    ‘‘‘

    #查询用户所在组有哪些权限
    # user = User.objects.first()
    # permissions = user.get_group_permissions()
    # print( permissions )
    # print(connection.queries)
    ‘‘‘
        执行的源sql如下:
        
        [{‘sql‘: ‘SELECT @@SQL_AUTO_IS_NULL‘, ‘time‘: ‘0.001‘}, 
        {‘sql‘: ‘SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED‘, ‘time‘: ‘0.000‘}, 
        {‘sql‘: ‘SELECT `app01_user`.`id`, `app01_user`.`password`, `app01_user`.`last_login`, `app01_user`.`is_superuser`, `app01_user`.`telephone`, `app01_user`.`email`, `app01_user`.`username`, `app01_user`.`is_active` FROM `app01_user` ORDER BY `app01_user`.`id` ASC LIMIT 1‘, ‘time‘: ‘0.001‘}, 
        {‘sql‘: ‘SELECT VERSION()‘, ‘time‘: ‘0.000‘}, 
        {‘sql‘: ‘SELECT `django_content_type`.`app_label`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `auth_group_permissions` ON (`auth_permission`.`id` = `auth_group_permissions`.`permission_id`) INNER JOIN `auth_group` ON (`auth_group_permissions`.`group_id` = `auth_group`.`id`) INNER JOIN `app01_user_groups` ON (`auth_group`.`id` = `app01_user_groups`.`group_id`) INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`) WHERE `app01_user_groups`.`user_id` = 1‘, ‘time‘: ‘0.003‘}]

        最后一条sql比较长,美化了下方便看:
        ‘SELECT `django_content_type`.`app_label`, `auth_permission`.`codename` 
                FROM `auth_permission` INNER JOIN `auth_group_permissions` ON 
                (`auth_permission`.`id` = `auth_group_permissions`.`permission_id`) 
                INNER JOIN `auth_group` ON 
                (`auth_group_permissions`.`group_id` = `auth_group`.`id`) 
                INNER JOIN `app01_user_groups` ON 
                (`auth_group`.`id` = `app01_user_groups`.`group_id`) 
                INNER JOIN `django_content_type` ON 
                (`auth_permission`.`content_type_id` = `django_content_type`.`id`)
                 WHERE `app01_user_groups`.`user_id` = 1‘
     ‘‘‘

    # 这里,有另外一个方法,判断用户是否有对应的权限, user.has_perm()
    # 1.首先判断user.permissions下有没有这个权限,如果有,就True
    # 2.如果user.permissions下没有这个权限,那么就会判断,他所属的分组
    user = User.objects.first()
    if user.has_perm(font.add_article):
        print("有这个添加文章的权限")
    else:
        print("没有添加文章的权限!")
    print( connection.queries)
    ‘‘‘
        打印的源sql如下:
        [{‘sql‘: ‘SELECT @@SQL_AUTO_IS_NULL‘, ‘time‘: ‘0.000‘}, 
        {‘sql‘: ‘SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED‘, ‘time‘: ‘0.001‘}, 
        {‘sql‘: ‘SELECT `app01_user`.`id`, `app01_user`.`password`, `app01_user`.`last_login`, `app01_user`.`is_superuser`, `app01_user`.`telephone`, `app01_user`.`email`, `app01_user`.`username`, `app01_user`.`is_active` FROM `app01_user` ORDER BY `app01_user`.`id` ASC LIMIT 1‘, ‘time‘: ‘0.001‘}, 
        {‘sql‘: ‘SELECT VERSION()‘, ‘time‘: ‘0.001‘}, 
        {‘sql‘: ‘SELECT `django_content_type`.`app_label`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `app01_user_user_permissions` ON (`auth_permission`.`id` = `app01_user_user_permissions`.`permission_id`) INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`) WHERE `app01_user_user_permissions`.`user_id` = 1‘, ‘time‘: ‘0.002‘}, 
        {‘sql‘: ‘SELECT `django_content_type`.`app_label`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `auth_group_permissions` ON (`auth_permission`.`id` = `auth_group_permissions`.`permission_id`) INNER JOIN `auth_group` ON (`auth_group_permissions`.`group_id` = `auth_group`.`id`) INNER JOIN `app01_user_groups` ON (`auth_group`.`id` = `app01_user_groups`.`group_id`) INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`) WHERE `app01_user_groups`.`user_id` = 1‘, ‘time‘: ‘0.002‘}]

    ‘‘‘

    return  HttpResponse( "操作分组!")

 

3、添加分组、并往分组里添加权限,数据库效果如下:

技术图片   技术图片

技术图片

 

 

 

 

 

 

4.将用户添加到对应的分组,效果如下:

技术图片

 

 技术图片

 

 

 

以上是关于django分组groupuserpermission的主要内容,如果未能解决你的问题,请参考以下文章

Django分组查询

Django 09-1模型层 查询(分组聚合)

Django:对表单字段进行分组

Django 管理表单中的分组字段

Django按变量分组

Django之路由(urls)层