django中定制权限六表

django中定制权限六表

权限六表

"""
基于权限的认证:
基于角色的认证:
	RBAC(Role-Based Access Control)
	三表机制:
	五表机制:
	Django采用六表:
"""

三表机制:

五表机制:

Django采用六表:

django六表模式展示。

自定义权限六表

1 models.py 定制user表

""" 相互访问
  
from django.db import models
""" 相互访问
User:  groups  user_permissions
Group:user_set permissions
Permission:user_set  group_set
解释说明:通过自定义模型类继承的模式实现了django自带权限六表的定制化
"""
class User(AbstractUser):
    mobile = models.CharField(max_length=11)
    class Meta:
        db_table = 'old_boy_user'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username


class Car(models.Model):
    name = models.CharField(max_length=64)
    is_delete = models.BooleanField(default=0)

    class Meta:
        db_table = 'old_boy_car'
        verbose_name = '汽车'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


2 amdin注册

from django.contrib import admin

from . import models

admin.site.register(models.Car)
admin.site.register(models.User) # 勿要忘记注册自己的定制的表

3 settings配置

# 配置自定义User表
AUTH_USER_MODEL = 'api.user'

4 查看定制化的模型表

5 测试代码

提示:测试前现在django的后台页面,添加好一个分组,然后添加一个用户,并且这个用户使用该分组。

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dg_proj.settings")
import django
django.setup()

""" 相互访问
User:  groups  user_permissions
Group:user_set permissions
Permission:user_set  group_set
"""
from api.models import User
from django.contrib.auth.models import Group
from django.contrib.auth.models import Permission

# user = User.objects.get(pk=2)  # type: User
# print(user.username)
# print(user.groups.first().name)
# print(user.user_permissions.first())

# group = Group.objects.get(pk=1)
# print(group)
# print(group.user_set.get(pk=2))
# print(group.permissions.get(pk=1))

# permission = Permission.objects.get(pk=19)
# print(permission)
# print(permission.user_set.first())
# permission = Permission.objects.get(pk=1)
# print(permission.group_set.first())
posted @ 2019-11-20 16:42  张明岩  阅读(502)  评论(0编辑  收藏  举报