1、model
from django.contrib.auth.models import User #django自带
class UserProfile(models.Model):
"""使用django 自带的用户控制权限的用户表"""
user = models.OneToOneField(User,on_delete=models.CASCADE) # django自带用户表User模块和自定义的用户关联
name = models.CharField(max_length=32)
roles = models.ManyToManyField("Role",blank=True,null=True)
def __str__(self):
return self.name
class Role(models.Model):
"""角色表"""
name = models.CharField(unique=True,max_length=32)
menus = models.ManyToManyField("Menu")
def __str__(self):
return self.name
2、view
def app_index(request):
return render(request, 'kingadmin/app_index.html')
3、html
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
{% for role in request.user.userprofile.roles.all %} <!--找到登陆用户的角色-->
<hr>
{% for menu in role.menus.all %} <!--找到角色对应的menu-->
<li>
<a href="{% if menu.url_type == 0 %}{% url menu.url_name %}{% else %} {{ menu.url_name }}{% endif %}" > <!--展示该用户的菜单-->
{{ menu.name }}
</a>
</li>
{% endfor %}
{% endfor %}
</ul>
</div>