一、权限管理表结构
model.py
from django.db import models # Create your models here. #权限表 class Permission(models.Model): # caption = models.CharField(max_length=32) parent_id = models.ForeignKey('Permission', related_name='k', to_field='id', null=True, blank=True) code = models.CharField(max_length=64, null=True,blank=True) method = models.CharField(max_length=16, null=True,blank=True) kwargs = models.CharField(max_length=128, null=True,blank=True) is_menu = models.BooleanField(default=False) def __str__(self): return self.caption #角色表 class Role(models.Model): name = models.CharField(max_length=32) def __str__(self): return self.name #角色对应的权限表 class RoleToPermission(models.Model): menu_id = models.ForeignKey(Permission, to_field='id') role_id = models.ForeignKey(Role, to_field='id') def __str__(self): return "%s-%s" %(self.menu_id.caption, self.role_id.name) #用户表 class UserInfo(models.Model): username = models.CharField(max_length=32) password = models.CharField(max_length=64) def __str__(self): return self.username #用户对应的权限表 class UserInfoToRole(models.Model): user_id = models.ForeignKey(UserInfo, to_field='id') role_id = models.ForeignKey(Role, to_field='id') def __str__(self): return '%s-%s' %(self.user_id.username, self.role_id.name)
二、easyui实现权限管理后台布局
1下载easyui:www.jeasyui.com/download/
2解压下载压缩包
拷贝若干目录文件到 django静态文件目录
拷贝至
3、修改模板
1)源码模板目录 demo/accordion/basic.html 修改为左侧栏目
2)源码模板文件 demo/tree/checkbox.html 修改为左侧栏目树形结构
、
三、权限数据表填充数据
admin.py
from django.contrib import admin from app01 import models # Register your models here. admin.site.register(models.Permission) admin.site.register(models.Role) admin.site.register(models.RoleToPermission) admin.site.register(models.UserInfo) admin.site.register(models.UserInfoToRole)
python manage.py createsuperuser
1.权限表创建数据
标题 一级菜单
创建二级菜单
2.创建角色数据
3.角色对应权限表创建数据
4.创建用户
5.用户对应角色数据
四、获取权限,登陆 以及用户信息添加到session
viwe.py
--login
def login(request): if request.method == 'POST': user = request.POST.get('user') pwd = request.POST.get('pwd') obj = models.UserInfo.objects.filter(username=user, password=pwd).first() if obj: # 当前用户信息保存至Session request.session['user_info'] = {'id': obj.id, 'name': obj.username} # 当前用户角色列表保存至Session #用户id对应角色 result_list = models.UserInfoToRole.objects.filter(user_id_id=obj.id).values('role_id_id') role_list = list(map(lambda x: x['role_id_id'], result_list)) #session添加到session request.session['role_list'] = role_list # 当前用户所有权限加入Session from django.db.models import Count, Min, Max, Sum permission_list = models.RoleToPermission.objects.filter(role_id__in=role_list).values( 'menu_id_id').annotate(c=Count('menu_id_id')).values('menu_id__caption', 'menu_id__parent_id', 'menu_id__code', 'menu_id__method', 'menu_id__kwargs') # 根据permission_id去重 permission_list = list(permission_list) request.session['permission_list'] = permission_list return redirect('/index/') return render(request, 'login.html')
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form action="/login/" method="POST"> <input type="text" name="user" /> <input type="password" name="pwd" /> <input type="submit" value="登录" /> </form> </body> </html>
group_by使用去重
获取去重的权限假如session
五、左侧菜单
viwe.py
1.myrender显示固定的数据结
def index(request): # 根据session中保存的menu_list生成动态菜单 # session_menu_list = request.session['menu_list'] # menu_list = build_tree(session_menu_list) # menu_list = [ { 'id': 1, 'text': '权限管理', 'url': None, 'children': [ { 'id': 4, 'text': '权限', 'url': 'permission' }, { 'id': 5, 'text': '用户', 'url': 'user' } ] }, { 'id': 2, 'text': '用户管理', 'url': None }, { 'id': 3, 'text': '帮助', 'url': None } ] return render(request, 'index.html')
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Full Layout - jQuery EasyUI Demo</title> <link rel="stylesheet" type="text/css" href="/static/easyui/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="/static/easyui/themes/icon.css"> <script type="text/javascript" src="/static/easyui/jquery.min.js"></script> <script type="text/javascript" src="/static/easyui/jquery.easyui.min.js"></script> <style> .crm-menu{ display: block; padding: 8px; border-bottom: 1px dotted #dddddd; } .crm-menu:hover{ background-color: #E0ECFF; } </style> {% block css %} {% endblock %} </head> <body class="easyui-layout"> <div data-options="region:'north',border:false" style="height:60px;background:#B3DFDA;padding:10px"> LOGO </div> <div data-options="region:'west',split:true,title:'West'" style="width:150px;"> <div id="aa" class="easyui-accordion" style="width:100%;"> #两次循环显示菜单 {% for menu in menu_list %} <div title="{{ menu.text }}" data-options="iconCls:'icon-ok'" style="overflow:auto;"> {% for child in menu.children %} <a id="menu_{{ child.url }}" href='/{{ child.url }}/' class='crm-menu'>{{ child.text }}</a> {% endfor %} </div> {% endfor %} </div> </div> <div data-options="region:'south',border:false" style="height:50px;background:#A9FACD;padding:10px;">south region</div> <div data-options="region:'center',title:'Center'"> {% block content %} {% endblock %} </div> {% block js %} {% endblock %} </body> </html>
自己写的列表显示
2.session里面的数据 自动生成固定格式的列表
view.py
def build_node(menu_list, dic): # for menu in menu_list: if menu['id'] == dic['menu_id__parent_id']: temp = {'id': dic['menu_id__id'],'text': dic['menu_id__caption'], 'url': dic['menu_id__code'],'children': []} menu['children'].append(temp) break else: build_node(menu['children'], dic) def build_tree(session_menu_list): # [ {menu_id__parent_id: None, 'menu_id__caption': '权限管理', 'menu_id__code': 'permission'},{},{} ] menu_list = [] # menu_list = [{...}] for dic in session_menu_list: if dic['menu_id__parent_id'] == None: temp = {'id': dic['menu_id__id'],'text': dic['menu_id__caption'], 'url': dic['menu_id__code'],'children': []} menu_list.append(temp) else: # 当前 build_node(menu_list, dic) return menu_list
3.创建myrender 每次返回自动把 menu加到session
viwe.py
def my_render(request, template_name, context=None, *args, **kwargs): session_menu_list = request.session['menu_list'] menu_list = build_tree(session_menu_list) if context: #context 是none 标题 context['menu_list'] = menu_list else: #否则是 菜单 context = {'menu_list': menu_list} return render(request, template_name, context, *args, **kwargs) def index(request): # 根据session中保存的menu_list生成动态菜单 # session_menu_list = request.session['menu_list'] # menu_list = build_tree(session_menu_list) # return my_render(request, 'index.html') def user(request): return my_render(request, 'user.html')
六 自动生成内容页 树形结构
html 修改模板 demo/tree/checkbox.html
viwe.py获得用户所有权限
代码:
viwe.py
def permission(request): # 当前用户所有的权限 return my_render(request, 'permission.html') def get_permission_tree(request): session_permission_list = request.session['permission_list'] permission_list = build_tree(session_permission_list) return HttpResponse(json.dumps(permission_list))
permission.html
{% extends 'layout/_layout.html' %} {% block content %} <div style="float: left;width: 300px"> <ul id="pers_tree" ></ul> <!-- <ul id="tt" class="easyui-tree" data-options="url:'/get_permission_tree/',method:'get',animate:true"></ul> --> </div> <div style="float: left;width: 600px"> <table id="dg"></table> </div> {% endblock %} {% block js %}
<script> $(function(){ InitTree(); }); #方法二 function InitTree(){ $('#pers_tree').tree({ url: '/get_permission_tree/', method: 'get', animate: true, onClick: function(node){ console.log(node.text,node.id); InitTable(node.id); InitPagination(); } }) } {% endblock %}
显示
七、根据id 获取下属权限表格
viwe.py
def get_child_permission(request): node_parent_id = request.GET.get('node_parent_id') page = request.GET.get('page') rows = request.GET.get('rows') page = int(page) rows = int(rows) start = (page - 1) * rows end = page * rows result_queryset = models.Permission.objects.filter(parent_id = node_parent_id).values('caption','code')[start:end] result_list = list(result_queryset) # [ {'caption': 'x', 'code': xxx} ] return HttpResponse(json.dumps(result_list))
permission.html +
{% extends 'layout/_layout.html' %} {% block content %} <div style="float: left;width: 300px"> <ul id="pers_tree" ></ul> #方法一 <!-- <ul id="tt" class="easyui-tree" data-options="url:'/get_permission_tree/',method:'get',animate:true"></ul> --> </div> <div style="float: left;width: 600px"> <table id="dg"></table> </div> {% endblock %} {% block js %} <script> $(function(){ InitTree(); }); function InitTree(){ $('#pers_tree').tree({ url: '/get_permission_tree/', method: 'get', animate: true, onClick: function(node){ console.log(node.text,node.id); InitTable(node.id); InitPagination(); } }) } function InitTable(node_parent_id){ $('#dg').datagrid({ title: '听不下去了', url: '/get_child_permission/', method: 'get', queryParams: { node_parent_id: node_parent_id }, columns: [[ { field: 'ck', checkbox: true }, { field: 'caption', title: '标题', width: 180, align: 'center' }, { field: 'code', title: 'URL', width: 180, align: 'center' } ]], toolbar: [ { text: '添加', iconCls: 'icon-add', handler: AddRow }, { text: '删除', iconCls: 'icon-remove', handler: RemoveRow }, { text: '修改', iconCls: 'icon-edit', handler: EditRow } ], pagePosition: 'both', pagination: true, pageSize: 10, pageNumber: 1, pageList: [10, 20, 50] }) } function AddRow(){ console.log('addrow'); } function RemoveRow(){ console.log('RemoveRow'); } function EditRow(){ console.log('EditRow'); } function InitPagination() { var pager = $('#dg').datagrid('getPager'); $(pager).pagination({ beforePageText: '第', afterPageText: '页 共{pages}页', displayMsg: '当前显示{from}-{to}条记录 共{total}条数据' }) } </script> {% endblock %}
显示效果: