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

创建后台管理数据库

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="">新增权限</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())

页面的一些效果

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

done。

最新文章

  1. 如何通过ps -ef|grep tomcat只获得你需要的查询进程,排除掉grep本身的进程信息
  2. Python面向对象入门
  3. v9 推荐位 排序问题解决办法
  4. ECharts本地部署
  5. hibernate annotation配置经验
  6. https,https的本地测试环境搭建,asp.net结合https的代码实现,http网站转换成https网站之后遇到的问题
  7. s实现指定时间自动跳转到某个页面
  8. C#设置textboox只能输入数字`
  9. C编译: makefile基础
  10. JS性能优化之怎么加载JS文件
  11. Git相关操作一
  12. $a=[1,2,3,4,5]; $b=[a,b,c,d,e]; 转成[[1,a],[2,b],[3,c],[4,d],[5,3]]
  13. 字体图标库 IcoMoon IconFont Font Awesome的使用
  14. day47 选择器优先级及嵌套关系
  15. Confluence 6 目录中的数据库
  16. Python全栈之路----文件处理
  17. Spring webFlux:坐等spring-boot-starter-data-mysql-reactive
  18. 不要使用 JWT 进行会话管理
  19. jqgrid 谈谈给表格设置列头事件、行事件、内容事件
  20. pyspark dataframe 常用操作

热门文章

  1. 写代码注意了,打死都不要用 User 这个单词
  2. Ansible之playbook的使用
  3. 在Github或Gitee上用hexo搭建个人博客
  4. 【转】调用百度API,HTML在线文字转语音播报
  5. 一台Linux服务器(4C8G配置)可以负载百万个连接?
  6. Oracle &#39;no privileges on tablespace 表空间名称&#39; 问题解决
  7. LPAT: Learning to Predict Adaptive Threshold for Weakly-supervised Temporal Action Localization [Paper Reading]
  8. Python之路【第二十五篇】:数据库之pymysql模块
  9. MVVM模式理解(转)
  10. 示例:自定义WPF底层控件UI库 HeBianGu.General.WpfControlLib V2.0版本