欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

django项目后台权限管理功能。

程序员文章站 2022-12-21 09:29:11
对后台管理员进行分角色,分类别管理,每个管理员登录账号后只显示自己负责的权限范围。 创建后台管理数据库 models.py文件内 创建和迁移数据库命令 应用目录下定义中间件,my_middleware.py文件,用来使权限生效。 settings.py文件中添加定义的中间件 写功能, 菜单管理功能 ......

对后台管理员进行分角色,分类别管理,每个管理员登录账号后只显示自己负责的权限范围。

创建后台管理数据库

models.py文件内

# 管理员表
class superuser(models.model):
    super_id=models.autofield(primary_key=true)
    super_name=models.charfield(max_length=255)
    super_pwd=models.charfield(max_length=255)
    role = models.manytomanyfield(to='role', )
#后台菜单表
class menu(models.model):
    """
    菜单表
    """
    name = models.charfield(verbose_name='菜单名', max_length=255)
    path = models.charfield(verbose_name='路径', max_length=255,
                            null=true,
                            blank=true)  # null :针对数据库,如果 null=true, 表示数据库的该字段可以为空,即在null字段显示为yes。blank :针对表单,如果 blank=true,表示你的表单填写该字段时可以不填,但是对数据库来说,没有任何影响
    pid = models.foreignkey(verbose_name='关联的权限', to='menu', null=true, blank=true, related_name='parents',
                            help_text='父id', on_delete=models.cascade)

    # def __str__(self):
    #     return self.name

# 权限表
class permission(models.model):
    """
    权限表
    """
    name = models.charfield(verbose_name='权限名', max_length=255)
    path = models.charfield(verbose_name='路径', max_length=255,
                            null=true,
                            blank=true)  # null :针对数据库,如果 null=true, 表示数据库的该字段可以为空,即在null字段显示为yes。blank :针对表单,如果 blank=true,表示你的表单填写该字段时可以不填,但是对数据库来说,没有任何影响
    pid = models.foreignkey(verbose_name='关联的权限', to='permission', null=true, blank=true, related_name='parents',
                            help_text='父id', on_delete=models.cascade)
    #1对多
    menu = models.foreignkey(verbose_name='所属菜单', to='menu', null=true, blank=true, help_text='null表示不是菜单;非null表示是二级菜单',on_delete=models.cascade)
    # def __str__(self):
    #     return self.name

#角色表
class role(models.model):
    """
    角色表
    """
    name = models.charfield(verbose_name='角色名', max_length=255)
    access = models.charfield(verbose_name='可以访问的权限', max_length=255,
                              null=true,
                              blank=true)

创建和迁移数据库命令

python manage.py makemigrations
python manage.py migrate

应用目录下定义中间件,my_middleware.py文件,用来使权限生效。

from django.utils.deprecation import middlewaremixin
from django.shortcuts import httpresponse,redirect
from blog.models import role,superuser,menu,permission
import json

class authmiddleware(middlewaremixin):
    # 重写process_request方法
    def process_request(self, request):
        # 如果路径中包含back即为后台路径
        if 'back/' in request.path:
            # 获取用户登录的id
            super_id = request.session.get('super_id')
            # 判断是否登录,未登录则跳转至登录界面
            if not super_id and request.path != '/back/index/login/':
                return redirect('/back/index/login/')
            if super_id:
                # 判读当前登录用户,是否拥有访问此路径的权限
                role_objs = superuser.objects.filter(super_id=super_id).first().role.all().values('id')# 查询用户角色
                permission_obj = permission.objects.filter(path=request.path).first()  # 当前访问的权限id
                # 如果查询到有权限对象
                if permission_obj:
                    # 定义权限列表
                    permission_list=[]
                    # 遍历角色对象
                    for role in role_objs:
                        # print(role['id'])
                        # 获取角色的权限
                        access_obj=role.objects.filter(id=role['id']).first()
                        # 向权限列表中添加数据
                        permission_list.extend(access_obj.access.split(","))
                    # print(permission_list)
                    # 如果当前访问的权限id,不在权限列表汇总,返回无权限
                    if str(permission_obj.id) not in permission_list:
                        if request.method=='post':
                            res={'status':1,'info':'无权限'}
                            return httpresponse(json.dumps(res))
                    # if permission_obj.id not in permission_list:
                        return httpresponse("无权限")
                    else:
                        return none

settings.py文件中添加定义的中间件

middleware = [
    'django.middleware.security.securitymiddleware',
    'django.contrib.sessions.middleware.sessionmiddleware',
    'django.middleware.common.commonmiddleware',
    'django.middleware.csrf.csrfviewmiddleware',
    'django.contrib.auth.middleware.authenticationmiddleware',
    'django.contrib.messages.middleware.messagemiddleware',
    'django.middleware.clickjacking.xframeoptionsmiddleware',
    'blog.my_middlewares.authmiddleware',
]

写功能,

菜单管理功能

前端引入

<script src="/static/jquery-1.8.2.min.js"></script>
<script src="/static/layer/layer.js"></script>

前端html

#菜单列表、删除,编辑
<table class="tablelist">
    <thead>
    <tr>
        {#                    <th><input name="" type="checkbox" value="" checked="checked"/></th>#}
        <th>菜单序号<i class="sort"><img src="/static/back/images/px.gif"/></i></th>
        <th>菜单名称</th>
        <th>菜单等级</th>
        <th>上级菜单</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    {% for v in menu_list %}
        <tr>
            {#                        <td><input name="" type="checkbox" value=""/></td>#}
            <td>{{ forloop.counter }}</td>
            <td>{{ v.name }}</td>

            <td>
                <h6>一级菜单</h6>
            </td>
            <td>
                <h6>无</h6>
            </td>

            <td>
                <a href="javascript:;" data-id="{{ v.id }}" class="tablelink del_1">删除</a>&nbsp;&nbsp;
                <a href="/back/article/editor_menu_f/{{ v.id }}/" data-editor="{{ v.super_id }}"
                   class="tablelink editor">编辑</a>

            </td>


        </tr>
    {% endfor %}
    {% for v in menu_list_z %}
        <tr>
            {#                        <td><input name="" type="checkbox" value=""/></td>#}
            <td>{{ forloop.counter }}</td>
            <td>{{ v.name }}</td>

            <td>
                <h6>二级菜单</h6>
            </td>
            <td>
                <h6>{{ v.pid.name }}</h6>
            </td>

            <td>
                <a href="javascript:;" data-id="{{ v.id }}" class="tablelink del_2">删除</a>&nbsp;&nbsp;
                <a href="/back/article/editor_menu_z/{{ v.id }}/" data-editor="{{ v.super_id }}"
                   class="tablelink editor">编辑</a>

            </td>


        </tr>
    {% endfor %}

    </tbody>
</table>

#新增菜单
<form method="post" onsubmit="return false" id="menu_1">
    {% csrf_token %}
    <table class="tablelist">
        <thead>
        <tr>
            <th>新增一级菜单</th>
        </tr>
        <tr>
            <th style="border: 1px #9c9c9c solid;"><input type="text" placeholder="输入菜单名称" name="menu_name">
            </th>
        </tr>
        </thead>
    </table>
    <input type="button" value="提交" id="onsubmit" style="width: 100px; height: 30px;">
</form>
<br><br>
<form method="post" onsubmit="return false" id="menu_2">
    {% csrf_token %}
    <table class="tablelist">
        <thead>
        <tr>
            <th>新增二级菜单</th>
        </tr>
        <tr>
            <th style="border: 1px #9c9c9c solid;"><input type="text" placeholder="输入菜单名称" name="menu_name">
            </th>
            <th style="border: 1px #9c9c9c solid;"><input type="text" placeholder="输入菜单路径" name="menu_path">
            </th>


            <th>

                <select name="pid">
                    <option value="" style="display: none">选择所属一级菜单</option>
                    {% for v in menu_list %}
                        <option value="{{ v.id }}">{{ v.name }}</option>
                    {% endfor %}
                </select>

            </th>


        </tr>
        </thead>
    </table>

    <input type="button" value="提交" id="onsubmit2" style="width: 100px; height: 30px;">
</form>

前端js

<script>
    {#    添加一级菜单#}
    $(document).ready(function () {
        $('#onsubmit').click(function () {
            $.post('/back/article/menu_add/', $('#menu_1').serialize(), function (data) {
                if (data['status'] == 0) {
                    layer.msg(data['info'])
                    location.href='/back/article/menu_add/'
                } else {
                    layer.msg(data['info'])
                }
            }, 'json')
        })
    })
    {#添加二级菜单#}
    $(document).ready(function () {
        $('#onsubmit2').click(function () {
            $.post('/back/article/menu_add1/', $('#menu_2').serialize(), function (data) {
                if (data['status'] == 0) {
                    layer.msg(data['info'])
                    location.href='/back/article/menu_add/'
                } else {
                    layer.msg(data['info'])
                }
            }, 'json')
        })
    });
{#    删除一级菜单#}
$(document).ready(function () {
        $('.del_1').click(function () {
            _this=this;
            layer.confirm('删除一级菜单会连带删除所属二级菜单,确定删除吗?',{
                btn:['确定','取消']
            },function(){
                id=$(_this).data('id');
                $.post('/back/article/menu_del_f/',{'id':id,'csrfmiddlewaretoken':'{{ csrf_token }}'},function (data) {
                if (data['status']==0){
                    layer.msg(data['info'])
                    location.href='/back/article/menu_add/'
                }else {
                    layer.msg(data['info'])
                }
            },'json')
            },function () {

            })

        })
    })
    {#    删除二级菜单#}
$(document).ready(function () {
        $('.del_2').click(function () {
            _this=this;
            layer.confirm('确定删除这个二级菜单吗?',{
                btn:['确定','取消']
            },function(){
                id=$(_this).data('id');
                $.post('/back/article/menu_del_z/',{'id':id,'csrfmiddlewaretoken':'{{ csrf_token }}'},function (data) {
                if (data['status']==0){
                    layer.msg(data['info'])
                    location.href='/back/article/menu_add/'
                }else {
                    layer.msg(data['info'])
                }
            },'json')
            },function () {

            })

        })
    })
</script>

路由

# 新增一级菜单
re_path('article/menu_add/', article.menu_add, name='article/menu_add/'),
# 新增二级菜单
re_path('article/menu_add1/', article.menu_add1, name='article/menu_add1/'),
# 删除一级菜单
re_path('article/menu_del_f/', article.menu_del_f, name='article/menu_del_f/'),
# 删除二级菜单
re_path('article/menu_del_z/', article.menu_del_z, name='article/menu_del_z/'),
# 编辑一级菜单
re_path('article/editor_menu_f/(\d+)/',article.editor_menu_f,name='article/editor_menu_f/'),
# 编辑二级菜单
re_path('article/editor_menu_z/(\d+)/',article.editor_menu_z,name='article/editor_menu_z/'),

方法

from collections import ordereddict

# 新增一级菜单
def menu_add(request):
    menu_list=menu.objects.filter(pid__isnull=true)
    menu_list_z=menu.objects.filter(pid__isnull=false)
    if request.method=='post':
        res = {'status': none, 'info': none}
        menu_name=request.post.get('menu_name')
        menu_name_f_obj=menu.objects.filter(name=menu_name,pid_id__isnull=true)
        if menu_name_f_obj:
            res = {'status': 1, 'info': '菜单名称已存在,请重新编辑'}
            return httpresponse(json.dumps(res))
        if menu_name:
            menu_obj=menu.objects.create(name=menu_name)
            if menu_obj:
                permission_obj=permission.objects.create(name=menu_name,menu_id=menu_obj.id)
                res = {'status': 0, 'info': '添加成功'}
            else:
                res = {'status': 1, 'info': '添加失败'}
            return httpresponse(json.dumps(res))
        else:
            res = {'status': 2, 'info': '请输入菜单名称'}
        return  httpresponse(json.dumps(res))
    return render(request,'article/menu_add.html',locals())
    
    # 添加二级菜单
def menu_add1(request):
    if request.method=='post':
        res = {'status': none, 'info': none}
        menu_name=request.post.get('menu_name')
        menu_path=request.post.get('menu_path')
        pid=request.post.get('pid')
        menu_name_z_obj = menu.objects.filter(name=menu_name,pid_id__isnull=false)
        if menu_name_z_obj:
            res = {'status': 1, 'info': '菜单名称已存在,请重新编辑'}
            return httpresponse(json.dumps(res))
        if not menu_name:
            res = {'status': 1, 'info': '未输入菜单名称'}
            return httpresponse(json.dumps(res))
        if not menu_path:
            res = {'status': 2, 'info': '未输入菜单路径'}
            return httpresponse(json.dumps(res))
        if not pid:
            res = {'status': 3, 'info': '未选择所属一级菜单'}
            return httpresponse(json.dumps(res))
        menu_obj=menu.objects.create(name=menu_name,path=menu_path,pid_id=pid)
        if menu_obj:
            menu_id=permission.objects.filter(menu_id=pid).first().id
            permission_obj=permission.objects.create(name=menu_name,path=menu_path,menu_id=menu_obj.id,pid_id=menu_id)
            res = {'status': 0, 'info': '添加成功'}
        else:
            res = {'status': 1, 'info': '添加失败'}
        return httpresponse(json.dumps(res))


# 删除一级菜单
def menu_del_f(request):
    if request.method=='post':
        res = {'status': none, 'info': none}
        menu_id=request.post.get('id')
        if not menu_id:
            res = {'status': 1, 'info': '异常'}
            return httpresponse(json.dumps(res))
        menu_f=menu.objects.filter(id=menu_id).delete()
        menu_z=menu.objects.filter(pid_id=menu_id).delete()
        permission_f=permission.objects.filter(menu_id=menu_id).values('id').first()
        # print(permission_f['id'])
        if permission_f:
            permission_z=permission.objects.filter(pid_id=permission_f['id']).delete()
        permission_f = permission.objects.filter(menu_id=menu_id).delete()
        if menu_f and permission_f:
            res = {'status': 0, 'info': '删除成功'}
        else:
            res = {'status': 2, 'info': '删除失败'}
        return httpresponse(json.dumps(res))
    return httpresponse('ok')
    
# 删除二级菜单
def menu_del_z(request):
    if request.method=='post':
        res = {'status': none, 'info': none}
        menu_id=request.post.get('id')
        if not menu_id:
            res = {'status': 1, 'info': '异常'}
            return httpresponse(json.dumps(res))
        menu_obj=menu.objects.filter(id=menu_id).delete()
        permission_obj=permission.objects.filter(menu_id=menu_id).delete()
        if menu_obj and permission_obj:
            res = {'status': 0, 'info': '删除成功'}
        else:
            res = {'status': 2, 'info': '删除失败,请联系技术人员'}
        return httpresponse(json.dumps(res))
    return httpresponse('ok')
    
# 编辑一级菜单
def editor_menu_f(request,id):
    menu_f_obj=menu.objects.filter(id=id).first().name
    if request.method=='post':
        menu_f_name=request.post.get('menu_f')
        if not menu_f_name:
            res = {'status': 1, 'info': '未输入菜单名称'}
            return httpresponse(json.dumps(res))
        menu_f_name_obj=menu.objects.filter(name=menu_f_name,pid_id__isnull=true)
        if menu_f_name_obj and menu_f_name != menu_f_obj:
            res = {'status': 1, 'info': '菜单名称已存在,请重新编辑'}
            return httpresponse(json.dumps(res))
        menu_obj=menu.objects.filter(id=id).update(name=menu_f_name)
        permission_obj=permission.objects.filter(menu_id=id).update(name=menu_f_name)
        if menu_obj and permission_obj:
            res = {'status': 0, 'info': '修改成功'}
        else:
            res = {'status': 1, 'info': '修改失败,请联系技术人员'}
        return httpresponse(json.dumps(res))

    return render(request,'article/editor_menu_f.html',locals())

# 编辑二级菜单
def editor_menu_z(request,id):
    menu_obj=menu.objects.filter(id=id).first()
    menu_list=menu.objects.filter(pid_id__isnull=true)
    if request.method == 'post':
        res = {'status': none, 'info': none}
        menu_name = request.post.get('menu_name')
        menu_path = request.post.get('menu_path')
        pid = request.post.get('pid')
        menu_name_z_obj = menu.objects.filter(name=menu_name, pid_id__isnull=false)
        if menu_name_z_obj and menu_name !=menu_obj.name:
            res = {'status': 1, 'info': '菜单名称已存在,请重新编辑'}
            return httpresponse(json.dumps(res))
        if not menu_name:
            res = {'status': 1, 'info': '未输入菜单名称'}
            return httpresponse(json.dumps(res))
        if not menu_path:
            res = {'status': 2, 'info': '未输入菜单路径'}
            return httpresponse(json.dumps(res))
        if not pid:
            res = {'status': 3, 'info': '未选择所属一级菜单'}
            return httpresponse(json.dumps(res))
        menu_obj = menu.objects.filter(id=id).update(name=menu_name, path=menu_path, pid_id=pid)
        if menu_obj:
            menu_id = permission.objects.filter(menu_id=pid).first().id
            permission_obj = permission.objects.filter(menu_id=id).update(name=menu_name, path=menu_path,
                                                       pid_id=menu_id)
            res = {'status': 0, 'info': '修改成功'}
        else:
            res = {'status': 1, 'info': '修改失败,请联系技术人员'}
        return httpresponse(json.dumps(res))


    return render(request,'article/editor_menu_z.html',locals())

#角色管理功能

前端引入

<script src="/static/jquery-1.8.2.min.js"></script>
<script src="/static/layer/layer.js"></script>

前端页面

<div id="tab2" class="tabson">
    <table class="tablelist">
        <thead>
        <tr>
            {#                    <th><input name="" type="checkbox" value="" checked="checked"/></th>#}
            <th>角色序号<i class="sort"><img src="/static/back/images/px.gif"/></i></th>
            <th>角色名称</th>
            {#                    <th>角色权限</th>#}
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        {% for v in role_obj %}
            <tr>
                {#                        <td><input name="" type="checkbox" value=""/></td>#}
                <td>{{ forloop.counter }}</td>
                <td>{{ v.name }}</td>
                {% if v.id == 4 %}
                    <td>
                        <h6>不能对超级管理员进行操作</h6>
                    </td>
                {% else %}
                    <td>
                        <a href="javascript:;" data-id="{{ v.id }}" class="tablelink del">删除</a>&nbsp;&nbsp;
                        <a href="/back/article/editor_role/{{ v.id }}/" data-editor="{{ v.super_id }}"
                           class="tablelink editor">编辑</a>
                        {#                            <a href="/back/article/role_add1/{{ v.id }}">&nbsp;&nbsp;&nbsp;>>设置权限</a>#}
                    </td>
                {% endif %}

            </tr>
        {% endfor %}


        </tbody>
    </table>

    {#######################################################################}


    <br><br>


</div>

<th><a href="/back/article/role_add1/">>>新增角色 </a></th>

新增角色的html

<script src="/static/jquery-1.8.2.min.js"></script>
<script src="/static/layer/layer.js"></script>

<form method="post" onsubmit="return false">
    {% csrf_token %}

    <table class="tablelist">
        <thead>
        <tr>
            <th>角色名称: &nbsp;&nbsp;<input type="text" name="role_name" placeholder="输入角色名称"></th>
        </tr>
        <tr>
            <th>
                选择所有权限: <br>
                {% for k,v in permission_all.items %}

                    &nbsp;&nbsp;&nbsp;
                    <input class="checkall" type="checkbox" name="check[]" id="{{ v.id }}" value="{{ v.id }}"
                            {% if  v.id|safe in permission_current %} checked="true'"  {% endif %}>
                    <label for="{{ v.id }}">{{ v.name }}</label>
                    <div>{% for v2 in v.children %}<input class="check" type="checkbox" id="{{ v2.id }}" value="{{ v2.id }}" name="check[]"  {% if  v2.id|safe in permission_current  %} checked="true'"  {% endif %}><label for="{{ v2.id }}">{{ v2.name }}</label>&nbsp; &nbsp; &nbsp; {% endfor %}</div>
                {% endfor %}
            </th>

        </tr>
        </thead>
    </table>

    <input type="button" value="提交" id="onsubmit" style="width: 100px; height: 30px;">
    <br><br>


</form>


#js
<script>
    {#    新建角色#}
    $(document).ready(function () {
        $('#onsubmit').click(function () {
            _this = this;
            id = $(_this).data('id');
            console.log(id);
            $.post('/back/article/role_add1/', $('form').serialize(), function (data) {
                if (data['status'] == 0) {
                    layer.msg(data['info']);
                    location.href='/back/article/role_add/'
                } else {
                    layer.msg(data['info'])
                }
            }, 'json')
        })
    });
{#局部全选全不选#}
$(document).on('click','.checkall',function () {
        $(this).next().next().children().prop('checked',$(this).prop('checked'))
    });
    $(document).on('click','.check',function () {
        $(this).parent().prev().prev().prop('checked',!$('%s:not(:checked)'%$(this).siblings()).length)
    });
</script>

前端js

<script>
    {#    增加职位#}
    $(document).ready(function () {
        $('#onsubmit').click(function () {
            $.post('/back/article/role_add/', $('#role_1').serialize(), function (data) {
                if (data['status'] == 0) {
                    layer.msg(data['info']);
                    location.href = '/back/article/role_add/'
                } else {
                    layer.msg(data['info'])
                }
            }, 'json')
        })
    });


    {#        删除管理员#}
    $('.del').click(function () {
        _this = this;
        layer.confirm('删除后不可恢复,确定删除吗?', {
            btn: ['确定', '取消']
        }, function () {
            id = $(_this).data('id');
            $.post('/back/article/role_del/', {'id': id, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, function (data) {
                if (data['status'] == 0) {
                    layer.msg(data['info']);
                    $(_this).parent().parent().remove()
                } else {
                    layer.msg(data['info'])
                }
            }, 'json')
        }, function () {

        });

    });
</script>

路由

# 角色列表
re_path('article/role_add/', article.role_add, name='article/role_add/'),
# 新增角色
re_path('article/role_add1/', article.role_add1, name='article/role_add1/'),
# 删除角色
re_path('article/role_del/', article.role_del, name='article/role_del/'),
# 编辑角色
re_path('article/editor_role/(\d+)/',article.editor_role,name='article/editor_role/'),

方法

# 角色列表
def role_add(request):
    permission_obj=permission.objects.filter(pid__isnull=false)
    role_obj=role.objects.all()
    permission_list=[]
    permission_obj_new=permission.objects.filter(pid__isnull=true)
    # for i in permission_obj_new:
    #     permission_list.append(i.id)
    # print(permission_list)
    # print(permission_obj_new)
    if request.method=='post':
        res = {'status': none, 'info': none}
        role=request.post.get('role')
        if not role:
            res = {'status': 1, 'info': '未输入职位名称'}
            return httpresponse(json.dumps(res))
        role_new=role.objects.create(name=role)
        if role_new:
            res = {'status': 0, 'info': '添加成功'}
        else:
            res = {'status': 2, 'info': '添加失败'}
        return httpresponse(json.dumps(res))
    return render(request,'article/role_add.html',locals())
    
    
# 新增角色
def role_add1(request):
    # permission_current1 = role.objects.filter(id=id).first()
    # if permission_current1.access:
    #     permission_current = permission_current1.access.split(",")
        # print(permission_current)
    permission_all = ordereddict()
    permission = permission.objects.filter(pid__isnull=true).all()
    for v in permission:
        permission2 = permission.objects.filter(pid=v.id).all()
        permission_all[v.id] = {
            'id': v.id,
            'name': v.name,
            'path': v.path,
            'children': permission2
        }
    # role_obj=role.objects.filter(id=id).first()
    # permission_obj = permission.objects.filter(pid__isnull=false)
    if request.method=='post':
        name=request.post.get('role_name')
        if not name:
            res = {'status': 1, 'info': '未输入角色名称'}
            return httpresponse(json.dumps(res))
        role_name_obj=role.objects.filter(name=name)
        if role_name_obj:
            res = {'status': 1, 'info': '角色名称已存在,请重新编辑'}
            return httpresponse(json.dumps(res))
        check=request.post.getlist('check[]')
        chk=','.join(check)
        role_obj = role.objects.create(name=name,access=chk)
        # new_role_obj=role.objects.filter(id=id).update(access=chk)
        if role_obj:
            res = {'status': 0, 'info': '添加成功'}
        else:
            res = {'status': 1, 'info': '添加失败'}
        return httpresponse(json.dumps(res))
    return render(request,'article/role_add1.html',locals())
    
    
# 删除角色
def role_del(request):
    if request.method=='post':
        res = {'status': none, 'info': none}
        role_id=request.post.get('id')
        if not role_id:
            res = {'status': 1, 'info': '未选择要删除的角色'}
            return httpresponse(json.dumps(res))
        role_del=role.objects.filter(id=role_id).delete()
        if role_del:
            res = {'status': 0, 'info': '删除成功'}
        else:
            res = {'status': 2, 'info': '删除失败,请联系技术人员'}
        return httpresponse(json.dumps(res))
    return httpresponse('ok')
    
    
# 编辑角色
def editor_role(request,id):
    role_obj=role.objects.filter(id=id).first()
    permission_current1 = role.objects.filter(id=id).first()
    if permission_current1.access:
        permission_current = permission_current1.access.split(",")
        # print(permission_current)
    permission_all = ordereddict()
    permission = permission.objects.filter(pid__isnull=true).all()
    for v in permission:
        permission2 = permission.objects.filter(pid=v.id).all()
        permission_all[v.id] = {
            'id': v.id,
            'name': v.name,
            'path': v.path,
            'children': permission2
        }
    if request.method=='post':
        check = request.post.getlist('check[]')
        # print(check)
        chk = ','.join(check)
        new_role_obj = role.objects.filter(id=id).update(access=chk)
        role_name=request.post.get('role_name')
        if not role_name:
            res = {'status': 1, 'info': '未输入角色名称'}
            return httpresponse(json.dumps(res))
        role_name_old_obj=role.objects.filter(name=role_name)
        if role_name_old_obj and role_name != role_obj.name:
            res = {'status': 1, 'info': '角色名称已存在,请重新编辑'}
            return httpresponse(json.dumps(res))
        role_name_obj=role.objects.filter(id=id).update(name=role_name)
        if role_name_obj and new_role_obj:
            res = {'status': 0, 'info': '修改成功'}
        else:
            res = {'status': 1, 'info': '修改失败,请联系技术人员'}
        return httpresponse(json.dumps(res))
    return render(request,'article/editor_role.html',locals())

#非菜单权限功能

前端页面

<table class="tablelist">
 <form method="post" onsubmit="return false">
{% csrf_token %}
    <thead>
     <tr>
        <th>权限序号</th>
        <th>权限名称</th>
        <th>操作</th>
    </tr>
    </thead>
 <thead>
     {% for v in permission_obj %}
    <tr>

        <th>{{ forloop.counter }}</th>
        <th>{{ v.name }}</th>

        <th>
            <a href="javascript:;" data-id="{{ v.id }}" class="tablelink del">删除</a>
            <a href="/back/article/editor_permission_it/{{ v.id }}" data-editor="{{ v.id }}" class="tablelink editor">编辑</a>

        </th>

    </tr>
    {% endfor %}
    </thead>
  </form>
</table>


<form method="post" onsubmit="return false" id="menu_2">
    {% csrf_token %}
    <table class="tablelist">
        <thead>
        <tr>
            <th colspan="2">新增权限</th>
        </tr>
        <tr>
            <th style="border: 1px #9c9c9c solid;"><input type="text" placeholder="输入权限名称" name="permission_name">
            </th>
            <th style="border: 1px #9c9c9c solid;"><input type="text" placeholder="输入权限路径" name="permission_path">
            </th>



        </tr>
        </thead>
    </table>

    <input type="button" value="提交" id="onsubmit2" style="width: 100px; height: 30px;">
</form>

前端js

<script>
    {#        删除其他权限#}
        $('.del').click(function () {
            _this=this
            layer.confirm('删除后不可恢复,确定删除吗?',{
                btn:['确定','取消']
            },function(){
                id=$(_this).data('id');
                $.post('/back/article/permission_it_del/',{'id':id,'csrfmiddlewaretoken':'{{ csrf_token }}'},function (data) {
                    if (data['status']==0){
                        layer.msg(data['info']);
                        $(_this).parent().parent().remove()
                    }else{
                        layer.msg(data['info'])
                    }
                },'json')
            },function () {

            });

        });

        {#添加权限#}
    $(document).ready(function () {
        $('#onsubmit2').click(function () {
            $.post('/back/article/permission_list/', $('#menu_2').serialize(), function (data) {
                if (data['status'] == 0) {
                    layer.msg(data['info']);
                    location.href='/back/article/permission_list/'
                } else {
                    layer.msg(data['info'])
                }
            }, 'json')
        })
    });
</script>

路由

# 其他权限
re_path('article/permission_list/',article.permission_list,name='article/permission_list/'),
# 删除其他权限
re_path('article/permission_it_del/',article.permission_it_del,name='article/permission_it_del/'),
# 编辑非菜单权限
re_path('article/editor_permission_it/(\d+)/',article.editor_permission_it,name='article/editor_permission_it/'),

方法

# 其他权限
def permission_list(request):
    permission_obj=permission.objects.filter(menu_id__isnull=true,pid_id__isnull=true)
    if request.method=='post':
        permission_name=request.post.get('permission_name')
        permission_path=request.post.get('permission_path')
        print(permission_name,permission_path)
        if not permission_name:
            res = {'status': 1, 'info': '未输入权限名称'}
            return httpresponse(json.dumps(res))
        if not permission_path:
            res = {'status': 2, 'info': '未输入权限路径'}
            return httpresponse(json.dumps(res))
        permission_name_obj=permission.objects.filter(name=permission_name,menu_id__isnull=true,pid_id__isnull=true)
        if permission_name_obj:
            res = {'status': 2, 'info': '权限名称已存在,请重新编辑'}
            return httpresponse(json.dumps(res))
        permission_new_obj=permission.objects.create(name=permission_name,path=permission_path)
        if permission_new_obj:
            res = {'status': 0, 'info': '添加成功'}
        else:
            res = {'status': 1, 'info': '添加失败'}
        return httpresponse(json.dumps(res))
    return render(request,'article/permisson_list.html',locals())
    
# 删除其他权限
def permission_it_del(request):
    if request.method=='post':
        id=request.post.get('id')
        permission_del_obj=permission.objects.filter(id=id).delete()
        if permission_del_obj:
            res = {'status': 0, 'info': '删除成功'}
        else:
            res = {'status': 0, 'info': '删除失败'}
        return httpresponse(json.dumps(res))
    return httpresponse('ok')

        
# 编辑其他权限
def editor_permission_it(request,id):
    permission_obj=permission.objects.filter(id=id).first()
    if request.method=='post':
        permission_name=request.post.get('permission_name')
        permission_path=request.post.get('permission_path')
        if not permission_name:
            res = {'status': 1, 'info': '未输入权限名称'}
            return httpresponse(json.dumps(res))
        if not permission_path:
            res = {'status': 2, 'info': '未输入权限路径'}
            return httpresponse(json.dumps(res))
        permission_name_obj=permission.objects.filter(name=permission_name)
        if permission_name_obj and permission_name != permission_obj.name:
            res = {'status': 1, 'info': '权限名称已存在,请重新编辑'}
            return httpresponse(json.dumps(res))
        permission_new_obj=permission.objects.filter(id=id).update(name=permission_name,path=permission_path)
        if permission_new_obj:
            res = {'status': 0, 'info': '修改成功'}
        else:
            res = {'status': 1, 'info': '修改失败,请联系技术人员'}
        return httpresponse(json.dumps(res))
    return render(request,'article/editor_permission_it.html',locals())

#管理员列表功能

前端html

<div id="tab2" class="tabson">

            <table class="tablelist">
                <thead>
                <tr>
{#                    <th><input name="" type="checkbox" value="" checked="checked"/></th>#}
                    <th>管理员序号<i class="sort"><img src="/static/back/images/px.gif"/></i></th>
                    <th>管理员名称</th>
                    <th>管理员权限</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                {% for v in super_obj %}
                    <tr>
{#                        <td><input name="" type="checkbox" value=""/></td>#}
                        <td>{{ forloop.counter }}</td>
                        <td>{{ v.super_name }}</td>
                        <td>{% for v2 in v.role.all %}
                            {{ v2.name }} &nbsp;&nbsp;
                            {% endfor %}
                        </td>

                    {% if v.role.first.id == 4 %}
                        <td>
                            <h6>不能对超级管理员进行操作</h6>
                        </td>
                        {% else %}
                        <td>
                            <a href="javascript:;" data-id="{{ v.super_id }}" class="tablelink del">删除</a>
                            <a href="/back/article/editor_back/{{ v.super_id }}" data-editor="{{ v.super_id }}" class="tablelink editor">编辑</a>
                            <a href="/back/article/permission_add1/{{ v.super_id }}">&nbsp;&nbsp;&nbsp;>>分配权限</a>
                        </td>
                    {% endif %}

                    </tr>
                {% endfor %}
                


                </tbody>
            </table>
        <div style="float: right;">
            <nav aria-label="page navigation">
                    <ul class="pagination">
                        {% if article_obj.has_previous %}
                            <li class="previous"><a
                                    href="/back/article/super_list/?page={{ article_obj.previous_page_number }}">上一页</a>
                            </li>
                        {% else %}
                            <li class="previous disabled"><a href="#">上一页</a></li>
                        {% endif %}





                        {% for num in pagerange %}
                            <li {% if num == currentpage %}class=" active"{% endif %}><a
                                    href="?page={{ num }}">{{ num }}</a></li>
                        {% endfor %}





                        {% if article_obj.has_next %}
                            <li class="next"><a
                                    href="/back/article/super_list/?page={{ article_obj.next_page_number }}">下一页</a>
                            </li>
                        {% else %}
                            <li class="next disabled"><a href="#">下一页</a></li>
                        {% endif %}

                    </ul>
                </nav>
        </div>

前端js

<script>
{#        删除管理员#}
        $('.del').click(function () {
            _this=this
            layer.confirm('删除后不可恢复,确定删除吗?',{
                btn:['确定','取消']
            },function(){
                id=$(_this).data('id');
                $.post('/back/article/super_delete/',{'id':id,'csrfmiddlewaretoken':'{{ csrf_token }}'},function (data) {
                    if (data['status']==0){
                        layer.msg(data['info']);
                        $(_this).parent().parent().remove()
                    }else{
                        layer.msg(data['info'])
                    }
                },'json')
            },function () {

            });

        });


    </script>

路由

# 给管理员重新分配角色(权限)
re_path('article/permission_add1/(\d+)/', article.permission_add1,name='article/permission_add1/'),
# 编辑管理员信息
re_path('article/editor_back/(\d+)/', article.editor_back,name='article/editor_back/'),
# 删除管理员
re_path('article/super_delete/', article.super_delete,name='article/super_delete/'),

方法

# 删除管理员
def super_delete(request):
    super_name=request.session.get('super_name')
    res={'status':none,'info':none}
    id=request.post.get('id')

    super_del=superuser.objects.filter(super_id=id).delete()
    if super_del:
        res['status']=0
        res['info']='删除成功'
    else:
        res['status'] = 1
        res['info'] = '删除失败'
    return httpresponse(json.dumps(res))
    
    
# 修改管理员信息
def editor_back(request,id):
    super_name = request.session.get('super_name')
    res = {'status': none, 'info': none}
    super_obj=superuser.objects.filter(super_id=id).first()
    if request.method=='post':

        super_name = superuser.objects.filter(super_id=id).first().super_name
        new_super_name = request.post.get('super_name')
        new_super_pwd = request.post.get('super_pwd')
        if not new_super_name:
            res = {'status': 4, 'info': '未填写帐号'}
            return httpresponse(json.dumps(res))
        if not new_super_pwd:
            res = {'status': 5, 'info': '未填写密码'}
            return httpresponse(json.dumps(res))
        old_super_name = superuser.objects.filter(super_name=new_super_name)
        if old_super_name and new_super_name != super_name:
            res = {'status': 1, 'info': '帐号已存在'}
        else:
            super_obj = superuser.objects.filter(super_id=id).update(super_name=new_super_name,
                                                                     super_pwd=make_password(new_super_pwd))
            if super_obj:
                res = {'status': 0, 'info': '修改成功'}
            else:
                res = {'status': 2, 'info': '修改失败'}
            return httpresponse(json.dumps(res))
        return httpresponse(json.dumps(res))

        # return httpresponse(json.dumps(res),locals())
    return render(request,'article/editor_back.html',locals())
    
    
# 分配权限
def permission_add1(request,id):
    print(id)
    super_obj=superuser.objects.filter(super_id=id).first()
    role_obj=role.objects.all()
    role_obj_new=superuser.objects.filter(super_id=id).first().role.all().values('id')
    role_list=[]
    for i in role_obj_new:
        print(i['id'])
        role_list.append(str(i['id']))
    print(role_list)
    if request.method=='post':
        res = {'status': none, 'info': none}
        check=request.post.getlist('check[]')
        super_obj.role.clear()
        for i in check:
            super_obj.role.add(i)

        res = {'status': 0, 'info': '成功'}
        return httpresponse(json.dumps(res))
    return render(request,'article/permission_add1.html',locals())

#添加管理员功能

前端html

<form method="post" onsubmit="return false">
        {% csrf_token %}
        <table class="tablelist">
            <thead>
            <tr>
            <th>超级管理员名称<i class="sort"><img src="/static/back/images/px.gif" /></i></th>
            <th>密码</th>
            <th>设置权限</th>
            <th>操作</th>
            </tr>
            <tr>
                <th style="border: 1px #9c9c9c solid;"><input type="text" placeholder="输入管理员名称" name="super_name"></th>
                <th style="border: 1px #9c9c9c solid;"><input type="password" placeholder="输入密码" name="super_pwd"></th>
                <th style="border: 1px #9c9c9c solid;">{% for v in role_obj %}

                                &nbsp;&nbsp;&nbsp; {% if v.id == 4 %}
                                    <input type="checkbox" name="check[]" id="{{ v.id }}" value="{{ v.id }}"
                                            {% if  v.id|safe in role_list %} checked="true'"  {% endif %} onclick="layer.msg('普通用户不可设为超级管理员'); return false">
                                    <label for="{{ v.id }}">{{ v.name }}</label>
                                {% else %}
                                <input type="checkbox" name="check[]" id="{{ v.id }}" value="{{ v.id }}"
                                        {% if  v.id|safe in role_list %} checked="true'"  {% endif %}>
                                <label for="{{ v.id }}">{{ v.name }}</label>
{#                                <div>{% for v2 in v.children %}<input type="checkbox" id="{{ v2.id }}" value="{{ v2.id }}" name="check[]"  {% if  v2.id|safe in permission_current  %} checked="true'"  {% endif %}><label for="{{ v2.id }}">{{ v2 }}</label>&nbsp; &nbsp; &nbsp; {% endfor %}</div>#}
                {% endif %}
                {% endfor %}</th>

                <th style="border: 1px #9c9c9c solid;"><input type="button" value="提交" id="onsubmit"></th>
            </tr>
            </thead>



        </table>
    </form>

前端js

<script>
        $(document).ready(function () {
            $('#onsubmit').click(function () {
                $.post('/back/article/super_add/',$('form').serialize(),function (data) {
                    if (data['status']==0){
                        layer.msg(data['info']);
                        location.href='/back/article/super_list/'
                    } else {
                        layer.msg(data['info'])
                    }
                },'json')
            })
        })
    </script>

路由

# 添加管理员功能
re_path('article/super_add/', article.super_add, name='article/super_add/'),

方法

# 新增管理员
def super_add(request):
    role_obj = role.objects.all()
    if request.method == 'post':
        res={"status":none,'info':none}
        super_name=request.post.get('super_name')
        super_back_pwd=request.post.get('super_pwd')
        super_pwd=make_password(request.post.get('super_pwd'))

        if super_name and super_back_pwd:
            super_old_obj=superuser.objects.filter(super_name=super_name)
            if super_old_obj:
                res['status'] = 3
                res['info'] = '管理员名称已存在'
                return httpresponse(json.dumps(res))
            super_obj = superuser.objects.create(super_name=super_name, super_pwd=super_pwd)
            if super_obj:
                check = request.post.getlist('check[]')
                super_obj.role.clear()
                for i in check:
                    super_obj.role.add(i)
                res['status'] = 0
                res['info'] = '增加成功'
            else:
                res['status'] = 1
                res['info'] = '添加失败'
            return httpresponse(json.dumps(res))
        else:
            res['status'] = 2
            res['info'] = '请填写完整信息'
        return httpresponse(json.dumps(res))
    return render(request,'article/super_add.html',locals())

页面的一些效果

django项目后台权限管理功能。

django项目后台权限管理功能。

django项目后台权限管理功能。

给其中的管理员设置权限后,登录结果

django项目后台权限管理功能。

done。