看一下官方文档中 has_perm(perm) 的说明:
has_perm(perm )
Returns True if the user has the specified permission, where perm is in the format "<app label>.<permission codename> " . If the user is inactive, this method will always return False .
(其实也可以使用 request.user.get_all_permissions() 在终端中参看该用户的权限值,顺便就可以看到 perm 的格式了。)
下面说明一下<app label>.<permission codename> 分别代表什么,以 app authenication 中 models.py 的定义为例:
# -*- coding: utf-8 -*-
from django.db import models
class Auth_control(models.Model):
'''
用于权限控制(测试)
'''
class Meta:
permissions = (
('can_manage_users', '管理用户权限'),
)
from django.db import models
class Auth_control(models.Model):
'''
用于权限控制(测试)
'''
class Meta:
permissions = (
('can_manage_users', '管理用户权限'),
)
<app label> 的值为 authenication,
<permission codename> 的值为 can_manage_users,
所以参数 perm 的值就应该为 authentication.can_manage_users
然后就可以在 views.py 中做判断了:
if request.user.has_perm('authentication.can_manage_users'):
can = True
else:
can = False
can = True
else:
can = False
template 中:
{% if can %}
<a href="/newadmin/auth/">用户管理</a>
{% endif %}
<a href="/newadmin/auth/">用户管理</a>
{% endif %}