一:自定义权限验证
1.在model中的Meta类自定义权限码
class WorkUser(models.Model): username = models.CharField(u'用户名', max_length=10, unique=True) _password = models.CharField(u'密码', max_length=50, null=False) gender = models.CharField(u'性别', max_length=2, default=u'未知', null=False) class Meta: permissions = ( ("view_gender", "显示性别"), # 在Meta中自定义权限码 )
2.判断用户是否有权限码
class OtherPageAuth(LoginRequiredMixin, View): """ 用户是否已经验证 from django.contrib.auth.mixins import LoginRequiredMixin 指定局部的跳转url: login_url = "/work/auth_login" 全局: settings中 LOGIN_URL = '/work/auth_login' """ login_url = "/work/auth_login" # 没登录跳转到登陆界面,登录则正常执行 def get(self, request): print request.user.usere_permissons.all() # 用户的所有权限 ''' request.user.has_perm #判断用户是否拥有某个权限 request.user.has_perms([perms,]) # 判断用户是否有权限列表中的某个权限 ''' if request.user.has_perm("work_register.view_gender"): # app下的权限码 message = "you can do this" else: message = "don\'t move anywhere " print message return render(request, 'logok.html', locals())
二:视图的权限 继承PermissionRequiredMixin
class OtherPageAuth(LoginRequiredMixin, PermissionRequiredMixin, View): """ 用户是否已登录的验证,和用户是否有权限的判断 from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin 指定局部的跳转url: login_url = "/work/auth_login" 全局: settings中 LOGIN_URL = '/work/auth_login' """
# 单个权限 work_register为app名字 permission_required = "work_register.view_gender" # 没有权限就直接跳转 /work/auth_login 登陆页面
# 多个权限 多个权限都满足才行
# permission_required = ("work_register.permission_code1", "work_register.permission_code2") login_url = "/work/auth_login" # 没登录跳转到登陆界面,登录则正常执行 def get(self, request): return render(request, 'logok.html', locals())