权限管理原理:
不同角色拥有不同的角色权限,所以能否访问的页面也就不相同.
通过控制URL使用户访问到不同的URL,从而达到权限控制的目的.
设计权限数据库
权限管理
from django.db import models # Create your models here. class Userinfo(models.Model):
uname = models.CharField(max_length=30)
pwd = models.CharField(max_length=30) class Meta:
verbose_name_plural = '用户表' def __str__(self):
return self.uname class Juese(models.Model):
jsm = models.CharField(max_length=30) class Meta:
verbose_name_plural = '角色表' def __str__(self):
return self.jsm class UtoJ(models.Model):
u = models.ForeignKey(Userinfo,on_delete=models.CASCADE)
j = models.ForeignKey(Juese,on_delete=models.CASCADE) class Meta:
verbose_name_plural = '用户角色表' def __str__(self):
return "%s - %s "%(self.u.uname,self.j.jsm) class Quanxian(models.Model):
qxname = models.CharField(max_length=30)
url = models.CharField(max_length=30)
menu = models.ForeignKey('Menu',on_delete=models.CASCADE,null=True,blank=True) class Meta:
verbose_name_plural = '职能表' def __str__(self):
return "%s - %s "%(self.qxname,self.url) class Zsgc(models.Model):
zsgc = models.CharField(max_length=30)
url = models.CharField(max_length=30) class Meta:
verbose_name_plural = 'ZSGC表' def __str__(self):
return self.zsgc class Qtoz(models.Model):
q = models.ForeignKey(Quanxian,on_delete=models.CASCADE)
z = models.ForeignKey(Zsgc, on_delete=models.CASCADE)
class Meta:
verbose_name_plural = '权限表' def __str__(self):
return "%s - %s - %s/?p=%s"% (self.q.qxname,self.z.zsgc,self.q.url,self.z.url) class JtoQtoZ(models.Model):
j = models.ForeignKey(Juese, on_delete=models.CASCADE)
qz = models.ForeignKey(Qtoz, on_delete=models.CASCADE) class Meta:
verbose_name_plural = '角色权限表' def __str__(self):
return "%s >>> %s"% (self.j.jsm,self.qz) class Menu(models.Model):
Mname = models.CharField(max_length=32)
zgl = models.ForeignKey('self',related_name='z', on_delete=models.CASCADE,null=True,blank=True)
class Meta:
verbose_name_plural = '菜单栏' def __str__(self):
return self.Mname
获取用户信息、用户权限信息、菜单信息
# 取用户角色 uname juese
data = models.Juese.objects.filter(utoj__u__uname='xmei') # 获取当前用户角色的权限 uname_juese quanxian_zsgc
# 数据去重 (.values(字段).distinct()) 排除不必要的数据 .exclude(qz__q__menu__isnull=True)
data2 = models.JtoQtoZ.objects.filter(j__in=data).exclude(qz__q__menu__isnull=True).values('qz__q__qxname', 'qz__q__url','qz__q__menu').distinct()
# 获得菜单数据
data3 = models.Menu.objects.values("id", 'Mname', 'zgl').all()