Django权限管理
实现目标:
1、管理用户,添加角色,用户关联角色
2、添加权限、角色关联权限
3、添加动作、权限关联动作
4、添加菜单、权限关联菜单
实现动态生成用户权限菜单(可设置多级菜单嵌套)、根据前台URL自动选中菜单并折叠其余菜单
最终实现类似这样的效果:
菜单一
菜单二
一、首先是建立表格
models
from django.db import models # Create your models here. class User(models.Model): username = models.CharField(max_length=32) password = models.CharField(max_length=64) class Meta: verbose_name_plural = '用户表' def __str__(self): return self.username class Role(models.Model): role = models.CharField(max_length=32) class Meta: verbose_name_plural = '角色表' def __str__(self): return self.role class User2Role(models.Model): u = models.ForeignKey(User, on_delete=models.CASCADE) r = models.ForeignKey(Role, on_delete=models.CASCADE) class Meta: verbose_name_plural = '用户分配角色' def __str__(self): return '%s-%s' % (self.u.username, self.r.role) class Menu(models.Model): caption = models.CharField(max_length=32) parent = models.ForeignKey('self', related_name='p', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return '%s' % (self.caption,) class Permission(models.Model): caption = models.CharField(max_length=32) url = models.CharField(max_length=32) menu = models.ForeignKey(Menu, null=True, blank=True, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'URL表' def __str__(self): return '%s-%s' % (self.caption, self.url) class Action(models.Model): caption = models.CharField(max_length=32) code = models.CharField(max_length=32) class Meta: verbose_name_plural = '操作表' def __str__(self): return self.caption class Permission2Action(models.Model): p = models.ForeignKey(Permission, on_delete=models.CASCADE) a = models.ForeignKey(Action, on_delete=models.CASCADE) class Meta: verbose_name_plural = '权限表' def __str__(self): return '%s-%s:-%s?t=%s' % (self.p.caption, self.a.caption, self.p.url, self.a.code) class Permission2Action2Role(models.Model): p2a = models.ForeignKey(Permission2Action, on_delete=models.CASCADE) r = models.ForeignKey(Role, on_delete=models.CASCADE) class Meta: verbose_name_plural = '角色分配权限' def __str__(self): return '%s=>%s' % (self.r.role, self.p2a)
建立表后,用django的admin在表中添加一些数据
1、用户表:建立几个用户
2、角色表:建立几个角色,如:CEO\CTO\开发\客服\业务员
3、给用户分配角色
4、URL表:建立几个管理菜单,如:分类管理\报表管理\订单管理\用户管理
5、操作表:增\删\改\查
6、权限表:给URL添加操作内容
7、角色分配权限ÿ